0

I try to use paste0 in an ifelse() to create a conditioned new variable in a data table. 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.

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?

JuliaK
  • 129
  • 1
  • 1
  • 9
  • 2
    Where does i come from? – camille Dec 04 '19 at 18:20
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Dec 04 '19 at 19:02
  • @camille i comes from a loop. I have 8 variables testvart1, testva2, etc. For the sake of simplicity, I just defined i as 1 in the example. – JuliaK Dec 05 '19 at 08:55
  • You *haven't* defined it in the example – camille Dec 05 '19 at 15:44

2 Answers2

0

You need to iterate through your columns to define i, maybe you can try:

for(i in 1:length(grep("inc_2014_", colnames(data))))
{
    data[, paste0("inc_2014_",i) := ifelse(paste0("testvar",i) == 2014, 1, 0)]
}

dc37
  • 15,840
  • 4
  • 15
  • 32
0

It's not working, because you are trying to call the variable in the ifelse as a string.

Assuming i = 1, the result of paste0("testvar",i) is "testvar1" but ifelse needs testvar1, not as a string.

Use the function get() as follows and it should work.

data[, paste0("inc_2014_",i) := ifelse(get(paste0("testvar",i)) == 2014, 1, 0)]
Damiano
  • 16
  • 1