[英]paste0 in ifelse R
I try to use paste0 in an ifelse() to create a conditioned new variable in a data table.我尝试在 ifelse() 中使用 paste0 在数据表中创建一个有条件的新变量。 The code I use is the following:
我使用的代码如下:
data[, paste0("inc_2014_",i) := ifelse(paste0("testvar",i) == 2014, 1, 0)]
This does not work.这不起作用。 There is no error message but the values of inc_2014_i (in my test case inc_2014_1) are all 0 whereas ther should be a couple of hundreds 1.
没有错误消息,但 inc_2014_i 的值(在我的测试用例 inc_2014_1 中)都是 0,而应该有几百个 1。
If I test如果我测试
data[, paste0("inc_2014_",i) := ifelse(testvar1 == 2014, 1, 0)]
it works fine.它工作正常。
If I test如果我测试
paste0("testvar",i)
I get the correct variable as output.我得到正确的变量作为输出。
What am I doing wrong?我究竟做错了什么?
You need to iterate through your columns to define i, maybe you can try:您需要遍历您的列来定义 i,也许您可以尝试:
for(i in 1:length(grep("inc_2014_", colnames(data))))
{
data[, paste0("inc_2014_",i) := ifelse(paste0("testvar",i) == 2014, 1, 0)]
}
It's not working, because you are trying to call the variable in the ifelse as a string.它不起作用,因为您试图将 ifelse 中的变量作为字符串调用。
Assuming i = 1, the result of paste0("testvar",i)
is "testvar1"
but ifelse needs testvar1
, not as a string.假设 i = 1,
paste0("testvar",i)
是"testvar1"
但 ifelse 需要testvar1
,而不是字符串。
Use the function get()
as follows and it should work.使用函数
get()
如下,它应该可以工作。
data[, paste0("inc_2014_",i) := ifelse(get(paste0("testvar",i)) == 2014, 1, 0)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.