I'm new to R (started a few days ago) and coming from STATA. I am trying to create a loop to create dummy variables when a variable has value -9. I want to use a loop as I have got plenty of variables like this.
In the following, reflex_working is my dataframe and "A7LECTUR" etc are my variables. I am trying to create a dummy called "miss_varname" for each variable using the ifelse function.
varlist<-c("A7LECTUR", "A7GROASG", "A7RESPRJ", "A7WORPLC", "A7PRACTI",
"A7THEORI", "A7TEACHR", "A7PROBAL", "A7WRIASG", "A7ORALPR")
for (i in varlist){
reflex_working$miss_[i]<-ifelse(reflex_working$i==-9,1,0)
}
I get the following warnings for each iteration:
1: Unknown or uninitialised column: 'miss_'.
2: Unknown or uninitialised column: 'i'.
And no variable is created. I assume this must be something very trivial for everyone, but I have been trying for the last hour to create this kind of loop and have zero results to show.
Edit: I have something like:
A7LECTUR
1
2
1
4
-9
And would like, after the loop, to have a new column like:
reflex_working$miss_A7LECTUR
0
0
0
0
1
Hope this helps clarifying what I'm trying to achieve! Any help would be seriously appreciated.
Gabriele
reflex_working[[paste0("miss_", i)]]? Do you want to have columns like "miss_A7LECTUR", is that what you want? - Januaryreflex_working$miss_[i]with @January's code. - Roland