[英]Updating column using data.table when using global variable as column name
I am attempting to update a column in a data.table based on if the values in the column match an external variable.我正在尝试根据列中的值是否与外部变量匹配来更新 data.table 中的列。 The issue I am running into is using a global variable as a column name in data.table syntax.我遇到的问题是在 data.table 语法中使用全局变量作为列名。
Specifying the column name explicitly works as expected and updates the column.明确指定列名按预期工作并更新列。
dt[,`1:4880` := ifelse(`1:4880`==allele, 2, 1)]
However, I am unable to update the column when referring to it by a variable:但是,当通过变量引用该列时,我无法更新该列:
colname="1:4880"
dt[,..colname := ifelse(..colname==allele, 2, 1)]
Instead of updating the values in the column described by the variable name, the output is written to df$..colname instead. output 不会更新由变量名称描述的列中的值,而是写入 df$..colname。 Strangely, the output is correct so the ifelse function is working as intended, it's just writing the output to the wrong column name.奇怪的是,output 是正确的,所以 ifelse function 正在按预期工作,它只是将 output 写入错误的列名。
Is there a way to make the:= operator recognize a column name specified as a variable?有没有办法让:= 运算符识别指定为变量的列名?
On the lhs
, we can wrap with ()
to evaluate the value and either use get
or specify it in .SDcols
在lhs
上,我们可以用()
包装来评估值,然后使用get
或在.SDcols
中指定它
dt[, (colname) := ifelse(.SD[[1]] ==allele, 2, 1), .SDcols = colname]
It is not clear whether the allele
is another column or an object created with some value目前尚不清楚allele
是另一列还是具有某些价值的 object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.