我在使用data.table时遇到问题:如何转换列类?这是一个简单的例子:使用data.frame我没有转换它的问题,data.table我只是不知道如何:
df <- data.frame(ID=c(rep("A", 5), rep("B",5)), Quarter=c(1:5, 1:5), value=rnorm(10))
#One way: http://stackoverflow.com/questions/2851015/r-convert-data-frame-columns-from-factors-to-characters
df <- data.frame(lapply(df, as.character), stringsAsFactors=FALSE)
#Another way
df[, "value"] <- as.numeric(df[, "value"])
library(data.table)
dt <- data.table(ID=c(rep("A", 5), rep("B",5)), Quarter=c(1:5, 1:5), value=rnorm(10))
dt <- data.table(lapply(dt, as.character), stringsAsFactors=FALSE)
#Error in rep("", ncol(xi)) : invalid 'times' argument
#Produces error, does data.table not have the option stringsAsFactors?
dt[, "ID", with=FALSE] <- as.character(dt[, "ID", with=FALSE])
#Produces error: Error in `[<-.data.table`(`*tmp*`, , "ID", with = FALSE, value = "c(1, 1, 1, 1, 1, 2, …Run Code Online (Sandbox Code Playgroud) 我正在重新分类一个数据帧列中的值,并将这些值添加到另一列.以下脚本尝试将重分类函数应用于列,并将值输出到数据框中的另一列.
a = c(1,2,3,4,5,6,7)
x = data.frame(a)
# Reclassify values in x$a
reclass = function(x){
# 1 - Spruce/Fir = 1
# 2 - Lodgepole Pine = 1
# 3 - Ponderosa Pine = 1
# 4 - Cottonwood/Willow = 0
# 5 - Aspen = 0
# 6 - Douglas-fir = 1
# 7 - Krummholz = 1
if(x == 1) return(1)
if(x == 2) return(1)
if(x == 3) return(1)
if(x == 4) return(0)
if(x == 5) return(0)
if(x …Run Code Online (Sandbox Code Playgroud)