更改R中数据框列类别的最佳方法 [英] Best way to change class of column of data frame in R
问题描述
再一次看似简单的问题,但是……我在R中有一个名为"d1"的小数据框:
Once again a seemingly easy problem, but ... I have this small data frame named "d1" in R:
[,1] [,2]
[1,] "SHY" "75000"
[2,] "IGLIX" "25000"
我要做的就是将第2列中的字符转换为数字.经过一个小时的摆弄之后,我能弄清楚的是:
All I want to do is convert the characters in column 2 to numerics. After fiddling with this for an hour all I can figure out that works is:
a <- data.frame(d1[,1])
b <- data.frame(as.numeric(d1[,2]))
cbind(a, b)
这给了我
d1...1. as.numeric.d1...2..
1 SHY 75000
2 IGLIX 25000
当然有更简单的方法可以做到这一点?我尝试应用"失败.
Surely there is an easier way to do this? I tried "apply" unsuccessfully.
推荐答案
如果矩阵中有多个列,则可以一次完成所有操作,然后同时将这些列转换为其适当的类型.
If you have multiple columns in the matrix, you can do it all at once and convert the columns to their appropriate types at the same time.
## set up a matrix
m <- matrix(c("SHY", "75000", "IGLIX", "25000"), 2, byrow=TRUE)
## split by column, convert types, and make data frame
data.frame(
lapply(split(m, col(m)), type.convert, as.is = TRUE),
stringsAsFactors = FALSE
)
# X1 X2
# 1 SHY 75000
# 2 IGLIX 25000
type.convert()
将字符向量适当地转换为逻辑,整数,数字,复数或因数,因此我们需要使用 stringsAsFactors = FALSE
再次在第一列中获取字符.
type.convert()
converts a character vector to logical, integer, numeric, complex or factor as appropriate so we need to use stringsAsFactors=FALSE
to get characters in the first column again.
这篇关于更改R中数据框列类别的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!