Laf*_*tte 14 r data.table
下面的数据集具有我的大数据集的特征.我在data.table中管理它,有些列作为chr加载,尽管它们是数字并且我想将它们转换为数字并且这些列名称是已知的
dt = data.table(A=LETTERS[1:10],B=letters[1:10],C=as.character(runif(10)),D = as.character(runif(10))) # simplified version
strTmp = c('C','D') # Name of columns to be converted to numeric
# columns converted to numeric and returned a 10 x 2 data.table
dt.out1 <- dt[,lapply(.SD, as.numeric, na.rm = T), .SDcols = strTmp]
Run Code Online (Sandbox Code Playgroud)
我可以使用上面的代码将这2列转换为数字但是我想更新dt.我尝试使用:=然而它没有用.我在这里需要帮助!
dt.out2 <- dt[, strTmp:=lapply(.SD, as.numeric, na.rm = T), .SDcols = strTmp] # returned a 10 x 6 data.table (2 columns extra)
Run Code Online (Sandbox Code Playgroud)
我甚至尝试了下面的代码(编码像data.frame - 不是我理想的解决方案,即使它工作,因为我担心在某些情况下订单可能会改变)但它仍然无效.有人能告诉我为什么它不起作用吗?
dt[,strTmp,with=F] <- dt[,lapply(.SD, as.numeric, na.rm = T), .SDcols = strTmp]
Run Code Online (Sandbox Code Playgroud)
提前致谢!
Rol*_*and 33
如果通过引用分配:=(即,您不需要dt.out2 <-),则无需分配整个data.table .
您需要:=在括号中包装LHS 以确保它被评估(而不是用作名称).
像这样:
dt[, (strTmp) := lapply(.SD, as.numeric), .SDcols = strTmp]
str(dt)
#Classes ‘data.table’ and 'data.frame': 10 obs. of 4 variables:
# $ A: chr "A" "B" "C" "D" ...
# $ B: chr "a" "b" "c" "d" ...
# $ C: num 0.30204 0.00269 0.46774 0.08641 0.02011 ...
# $ D: num 0.151 0.0216 0.5689 0.3536 0.26 ...
# - attr(*, ".internal.selfref")=<externalptr>
Run Code Online (Sandbox Code Playgroud)
虽然Roland的答案更为惯用,但你也可以set在一个循环内考虑直接的东西.一种方法可能是这样的:
strTmp = c('C','D')
ind <- match(strTmp, names(dt))
for (i in seq_along(ind)) {
set(dt, NULL, ind[i], as.numeric(dt[[ind[i]]]))
}
str(dt)
# Classes ‘data.table’ and 'data.frame': 10 obs. of 4 variables:
# $ A: chr "A" "B" "C" "D" ...
# $ B: chr "a" "b" "c" "d" ...
# $ C: num 0.308 0.564 0.255 0.828 0.128 ...
# $ D: num 0.635 0.0485 0.6281 0.4793 0.7 ...
# - attr(*, ".internal.selfref")=<externalptr>
Run Code Online (Sandbox Code Playgroud)
从帮助页面开始?set,[.data.table如果这对您造成问题,这将避免一些开销.