user3154295
user3154295

Reputation: 1

coercing columns of a data frame to numeric

I can't get the following formula to coerce selected columns of a data frame to numeric

x<-read.csv("more.csv",colClasses="character")

test<-list(more[,10],more[,11],more[,12])
test2<-lapply(test,as.numeric)

But

is.numeric(more[,10])
[1] FALSE

When I use the following formula it works:

more[,10]<-as.numeric(more[,10])

is.numeric(more[,10])
[1] TRUE

I can't make out the error in the first formula used.

Upvotes: 0

Views: 1379

Answers (4)

paulmmluap
paulmmluap

Reputation: 1

Assuming your data frame is x and the column name is "value" :

x["value"] <- as.numeric(x[,"value"])

My example won't work if you eliminate the "," in x[,"value"]. I like this method due to its simplicity.

Upvotes: 0

Nad Pat
Nad Pat

Reputation: 3173

you can also use as.dataframe if as.numeric is not working.

Upvotes: 0

Tim
Tim

Reputation: 115

Because my work doesn't always necessarily use the same column locations, I personally would use a combination of josliber's approach and the original proposal. Create a vector of the column names you want to coerce, and use lapply to modify only those columns.

test <- as.vector(c("test1", "test2", "test3"))
more[test] = lapply(more[test], as.numeric)

Cheers

Upvotes: 1

josliber
josliber

Reputation: 44299

When you use test2 <- lapply(test, as.numeric), it is building a new list (called test2) with all the elements converted to be numeric. This does not change test and also does not change the data frame more.

You could convert columns 10, 11, and 12 to numeric in your data frame with something like:

more[,10:12] = as.numeric(more[,10:12])

Upvotes: 0

Related Questions