as.numeric数据集的子集
问题描述:
如何将第1列和第2列转换为数字?我试过这个对我来说很明显的东西,但没有。as.numeric数据集的子集
感谢
df <- data.frame(v1 = c(1,2,'x',4,5,6), v2 = c(1,2,'x',4,5,6), v3 = c(1,2,3,4,5,6), stringsAsFactors = FALSE)
as.numeric(df[,1:2])
答
我们可以使用lapply
遍历感兴趣的栏目,并转换为数字
df[1:2] <- lapply(df[1:2], as.numeric)
答
我建议这种方法,使用unlist
。如果可能的话,我特别喜欢“单线”方法。对于更多的选择和参考,我强烈建议这个美丽的post。
df <- data.frame(v1 = c(1,2,'x',4,5,6), v2 = c(1,2,'x',4,5,6),
v3 = (1,2,3,4,5,6), stringsAsFactors = FALSE)
df[, c("v1","v2")] <- as.numeric(as.character(unlist(df[, c("v1","v2")])))
Warning message:
NAs introduced by coercion
str(df)
data.frame': 6 obs. of 3 variables:
$ v1: num 1 2 NA 4 5 6
$ v2: num 1 2 NA 4 5 6
$ v3: num 1 2 3 4 5 6
答
可以使用矩阵索引没有任何隐藏的循环:
df[, 1:2] <- as.numeric(as.matrix(df[, 1:2]))
'DF [1:2] akrun
DF [ ,1:2] jogo