Ernie
Ernie

Reputation: 1153

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

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.

Upvotes: 3

Views: 8945

Answers (2)

Rich Scriven
Rich Scriven

Reputation: 99331

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.

Upvotes: 3

Ernie
Ernie

Reputation: 1153

@akrun’s answer solves this problem:

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

Upvotes: 0

Related Questions