Best way to change class of column of data frame in R

霸气de小男生 提交于 2021-02-04 21:31:07

问题


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"

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)

which gives me:

  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.


回答1:


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() 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.




回答2:


@akrun’s answer solves this problem:

data.frame(Col1= d1[,1], Col2=as.numeric(d1[,2]))


来源:https://stackoverflow.com/questions/28218220/best-way-to-change-class-of-column-of-data-frame-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!