Hello,
I need to create a list of variables. The new variables must have the values by a condition.
For example, I want to create v1_d based on v1.
bbdd$v1_d=ifelse(bbdd$v1==1,1,NA)
All the new variables have the same names, addiing a "_" to the end as I wrote up.
On Stata this is simple, but here I'm confused.
Thanks for your help
To help us help you, could you please prepare a reproducible example (reprex) illustrating your issue? Please have a look at this guide, to see how to create one:
This is an example:
I did it one by one the routine I desire.
k1=c(1,2,3,4,5)
k2=c(10,20,30,40,50)
k3=c(3,5,7,9,11)
k4=c(1,NA,1,1,NA)
kk=data.frame(k1,k2,k3,k4)
listv=c("k1","k2","k3") # list of variables
kk$k1_d=ifelse(kk$k1>3,1,NA)
kk$k2_d=ifelse(kk$k2>3,1,NA)
kk$k3_d=ifelse(kk$k3>3,1,NA)
kk
So, you can see the logic in creating a variables adding a "_d".
Now, imagine a list with many variables ( over 50).
Can I write a loop?
Or maybe using apply?
Tha'ts great, andresrcs!
One last thing...
Where did you add the "_d" to the new variables?
I suppose is here
list(d = ~ if_else(. > 3, 1, NA_real_)))
I mean, what if I need to perform almost the same, but instead of, for example, create k1_d I need to add the variable k1c or k1_pp. How do I edit your code?
Thanks again, andresrcs.
I noticed that reproduce k1_pp is simple. I just need to edit as this your code:
list(pp = ~ if_else(. > 3, 1, NA_real_)))
However, create k1c is different. Always the new variables come with the "_" line.
I know It's a bit annoying asking this...
How to edit the code to create "k1c"?
Even more, how to edit in order to create "ck1"?