我手动转换我的列数据类型:
data[,'particles'] <- as.numeric(as.character(data[,'particles']))
这不理想,因为数据可能会发展,我不确定会发生什么物种,例如它们可能是 - "nox", "no2", "co", "so2", "pm10"
以及将来更多。
无论如何都要自动转换它们吗?
我当前的数据集:
structure(list(particles = structure(c(1L, 3L, 5L, 5L, 5L, 5L,
5L, 5L, 5L, 5L, 5L, 6L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 4L, 4L,
4L, 3L, 3L, 3L, 3L, 5L, 6L, 5L, 3L), .Label = c("1", "11", "1.1",
"2", "2.1", "3.1"), class = "factor"), humidity = structure(c(4L,
7L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 6L, 1L, 1L, 1L,
5L, NA, NA, NA, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("0.1",
"1", "1.1", "1.3", "21", "2.1", "3"), class = "factor"), timestamp = c(1468833354929,
1468833365186, 1468833378458, 1468833538213, 1468833538416, 1468833538613,
1468833538810, 1468833538986, 1468833539172, 1468833539358, 1468833539539,
1468833554592, 1468833559059, 1468833562357, 1468833566225, 1468833573486,
1468840019118, 1468840024950, 1469029568849, 1469029584243, 1469029590530,
1469029622391, 1469029623598, 1469245154003, 1469245156533, 1469245156815,
1469245157123, 1469245162358, 1469245165911, 1469245170178, 1469245173788
), date = structure(c(1468833354.929, 1468833365.186, 1468833378.458,
1468833538.213, 1468833538.416, 1468833538.613, 1468833538.81,
1468833538.986, 1468833539.172, 1468833539.358, 1468833539.539,
1468833554.592, 1468833559.059, 1468833562.357, 1468833566.225,
1468833573.486, 1468840019.118, 1468840024.95, 1469029568.849,
1469029584.243, 1469029590.53, 1469029622.391, 1469029623.598,
1469245154.003, 1469245156.533, 1469245156.815, 1469245157.123,
1469245162.358, 1469245165.911, 1469245170.178, 1469245173.788
), class = c("POSIXct", "POSIXt"), tzone = "Asia/Singapore")), .Names = c("particles",
"humidity", "timestamp", "date"), row.names = c(NA, -31L), class = "data.frame")
它有particles
,humidity
,timestamp
,date
。
答案 0 :(得分:5)
使用mutate_if()
中的dplyr
的另一个选项,允许您对谓词返回的列TRUE
进行操作
library(dplyr)
df %>%
mutate_if(is.factor, funs(as.numeric(as.character(.))))
注意:此方法适用于您的follow up question
答案 1 :(得分:4)
如果您不知道哪些列需要事先转换,您可以从数据框中提取该信息,如下所示:
vec <- sapply(dat, is.factor)
给出:
> vec
particles humidity timestamp date
TRUE TRUE FALSE FALSE
然后,您可以使用此向量对lapply
# notation option one:
dat[, vec] <- lapply(dat[, vec], function(x) as.numeric(as.character(x)))
# notation option two:
dat[vec] <- lapply(dat[vec], function(x) as.numeric(as.character(x)))
如果要同时检测因子和字符列,可以使用:
sapply(dat, function(x) is.factor(x)|is.character(x))
答案 2 :(得分:2)
我们可以使用data.table
library(data.table)
setDT(df)[, lapply(.SD, function(x) if(is.factor(x)) as.numeric(as.character(x)) else x)]
答案 3 :(得分:1)
最好的选择是我认为 apply
你可以做到
newD<-apply(data[,"names"], 2,function(x) as.numeric(as.character(x)))
其中&#34;名称&#34;你把所有你想要的变量。然后应用2作为第二个参数将在第一个参数的所有列(如果你按行放置1)上应用函数(x)。您可以将其保存为新数据集或使用
重写旧数据集data[,"names"]<-apply....
答案 4 :(得分:1)
使用lapply
:
cols <- c("particles", "nox", ...)
data[,cols] <- lapply(data[,cols], function(x) as.numeric(as.character(x)))