2016-04-25 86 views
1

如何将第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]) 
+4

'DF [1:2] < - lapply(DF [1:2],as.numeric)'' – akrun

+1

DF [ ,1:2] < - as.numeric(as.matrix(df [,1:2]))' – jogo

回答

2

我们可以使用lapply遍历感兴趣的栏目,并转换为数字

df[1:2] <- lapply(df[1:2], as.numeric) 
0

我建议这种方法,使用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 
0

可以使用矩阵索引没有任何隐藏的循环:

df[, 1:2] <- as.numeric(as.matrix(df[, 1:2]))