如何将某些列仅转换为数字? [英] How to convert certain columns only to numeric?
问题描述
如何仅将数据框中的某些列转换为数字?
How can I convert certain columns only in a data frame to numeric?
例如,我有以下数据框:
For instance, I have this data frame:
structure(list(airport = c("EGLL", "EGLL"), xdate = c("2016-07-28",
"2016-07-31"), ws = c("6", "5"), wd = c("237", "299"), humidity = c("68",
"55")), .Names = c("airport", "xdate", "ws", "wd", "humidity"
), row.names = 1:2, class = "data.frame")
我只想转换 ws
, wd
和湿度
转换为数字,不 机场和xdate
。
I just want to convert ws
, wd
, and humidity
to numeric, not airport and xdate
.
如果我这样做:
columns <- sapply(weatherDF, is.character)
weatherDF[, columns] <- lapply(weatherDF[, columns, drop = FALSE], function(x) as.numeric(as.character(x)))
我正在转换机场
和 xdate
转换为数字,然后收到此警告:
I am converting airport
and xdate
to numberic, and then I get this warning:
Warning messages:
1: In FUN(X[[i]], ...) : NAs introduced by coercion
2: In FUN(X[[i]], ...) : NAs introduced by coercion
引入
现在我的数据框变为:
And now my data frame has become:
structure(list(airport = c(NA_real_, NA_real_), xdate = c(NA_real_,
NA_real_), ws = c(6, 5), wd = c(237, 299), humidity = c(68, 55
)), .Names = c("airport", "xdate", "ws", "wd", "humidity"), row.names = 1:2, class = "data.frame")
任何想法如何将它们转换
Any ideas how I can convert them properly?
推荐答案
1)您所有的列
是字符
列<-sapply(weatherDF,is.character)
airport xdate ws wd humidity
TRUE TRUE TRUE TRUE TRUE
2)为什么不简单?
weatherDF [,3:ncol(weatherDF)]<-lapply(3: ncol(weatherDF),函数(x)as.numeric(we atherDF [[x]]))
或
columns <-c("ws", "wd", "humidity")
weatherDF[, columns] <- lapply(columns, function(x) as.numeric(weatherDF[[x]]))
如果您不知道哪几列是数字,则可以尝试使用 tryCatch
like
If your dont know which columns is numeric you can try to find it using tryCatch
like
weatherDF[,1:ncol(weatherDF)]=lapply(1:ncol(weatherDF),function(x) {
tryCatch({
as.numeric(weatherDF[[x]])
},warning = function(w) {
weatherDF[[x]]}
)} )
这篇关于如何将某些列仅转换为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!