简体   繁体   English

将数据框的列强制为数字

[英]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.我无法弄清楚使用的第一个公式中的错误。

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.因为我的工作不一定总是使用相同的列位置,所以我个人会结合使用 josliber 的方法和原始提案。 Create a vector of the column names you want to coerce, and use lapply to modify only those columns.创建要强制的列名称的向量,并使用 lapply 仅修改这些列。

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

Cheers干杯

When you use test2 <- lapply(test, as.numeric) , it is building a new list (called test2 ) with all the elements converted to be numeric.当您使用test2 <- lapply(test, as.numeric) ,它正在构建一个新列表(称为test2 ),其中所有元素都转换为数字。 This does not change test and also does not change the data frame more .这不会改变test ,也不会more改变数据框。

You could convert columns 10, 11, and 12 to numeric in your data frame with something like:您可以使用以下内容将数据框中的第 10、11 和 12 列转换为数字:

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

如果as.numeric您也可以使用as.dataframe

Assuming your data frame is x and the column name is "value" :假设您的数据框是x并且列名是 "value" :

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

My example won't work if you eliminate the "," in x[,"value"] .如果您消除x[,"value"]的 "," ,我的示例将不起作用。 I like this method due to its simplicity.我喜欢这种方法,因为它很简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM