gpt4 book ai didi

r - 如何在特定列的data.table中将字符转换为数字?

转载 作者:行者123 更新时间:2023-12-03 21:04:57 24 4
gpt4 key购买 nike

下面的数据集具有我的大型数据集的特征。我在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]


我能够使用上面的代码将这两列转换为数字,但是我想更新dt。我尝试使用:=,但是没有用。我需要这里的帮助!

dt.out2 <- dt[, strTmp:=lapply(.SD, as.numeric, na.rm = T), .SDcols = strTmp] # returned a 10 x 6 data.table (2 columns extra)


我什至尝试了下面的代码(像data.frame一样编码-即使是可行的也不是我理想的解决方案,因为我担心在某些情况下顺序可能会更改),但仍然无法正常工作。有人可以让我知道为什么它不起作用吗?

dt[,strTmp,with=F] <- dt[,lapply(.SD, as.numeric, na.rm = T), .SDcols = strTmp]


提前致谢!

最佳答案

尽管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>


?set的帮助页面上,如果您遇到了问题,这可以避免某些 [.data.table开销。

关于r - 如何在特定列的data.table中将字符转换为数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29495281/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com