I have dataset1 with 11 variables like this
id e1 e1a e2 e2a ... e5 e5a
1 100 1 20 1 ... 15 2
2 100 1 20 2 ... 40 1
3 600 2 75 2 ... 300 2
4 400 1 80 1 ... 20 2
I would like to add 5 new variables conditional on the value of variables e#a==2. Resulting in dataset2 with 16 variables:
id e1 e1a e2 e2a ...e5 e5a e1m e2m...e5m
1 100 1 20 1 ...15 2 NA NA ... 15
2 100 1 20 2 ... 40 1 NA 20 ... NA
3 600 2 75 2 ...300 2 600 75 ... 300
4 400 1 80 1 ... 20 2 NA NA ... 20
I've tried using a for loop as follows:
Library(tidyverse)
for(i in 1:5) {
mutate(dataset1, eim=ifelse(eia==2,ei,"NA" ))
}
and it gives this error
Error: Problem with mutate() column eim.
ℹ eim = ifelse(eia == 2, ei, "NA").
x object 'eia' not found. Therefore I tried adding [] like this
for(i in 1:5) {
mutate(dataset1, e[i]m=ifelse(e[i]a==2,e[i],"NA" ))
}