[英]using eval, parse and as.character in data.table in R
I am having some trouble running a combination of eval, parse and as.character for a data.table. 我为data.table运行eval,parse和as.character的组合时遇到了一些麻烦。 I basically want to convert a given column of the data table to as.character output of the same column. 我基本上想将数据表的给定列转换为同一列的as.character输出。
library(data.table)
options(datatable.WhenJisSymbolThenCallingScope=TRUE)
# an options that I heard may solve the problem
iris2 <- data.table(iris)
VARS <- colnames(iris)
j <- 1
iris2[,eval(parse(text = paste0(VARS[j])))] # this works fine
iris2[,eval(parse(text = paste0(VARS[j]))) := as.character(eval(parse(text = paste0(VARS[j]))))]
#but this fails
From the looks of it, it appears the eval and parse functions work fine but when it comes to updating the column with := it seems to break. 从它的外观看,似乎eval和parse函数可以正常工作,但是在使用:=更新列时,它似乎已损坏。 Could someone tell me what the issue is? 有人可以告诉我问题是什么吗?
We can use the data.table
methods to transform the variables. 我们可以使用data.table
方法来转换变量。 Specify the 'VARS' or subset of 'VARS' ie 'VARS[j]' in .SDcols
, loop through the columns (in case we want to loop for multiple columns) and assign ( :=
) to the columns specified in 'VARS[j]` 在.SDcols
指定'VARS'或'VARS'的子集,即'VARS [j]',遍历各列(以防我们要循环多个列),并将( :=
)分配给“ VARS”中指定的列[j]`
iris2[, VARS[j] := lapply(.SD, as.character) , .SDcols = VARS[j]]
str(iris2)
#Classes ‘data.table’ and 'data.frame': 150 obs. of 5 variables:
#$ Sepal.Length: chr "5.1" "4.9" "4.7" "4.6" ...
#$ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
#$ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
#$ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
#$ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.