Reputation: 73
I would like to run a loop over a series of variables (Change_1 to Change_12) to check if they meet certain conditions. Based on that, I want to create dummies. How do I do this loop in R?
generate newvariable=0
forvalues i = 1/12 {
replace newvariable=1 if Change_`i'==1 | Change_`i'== 6| Change_`i'==9
}
Upvotes: 0
Views: 988
Reputation: 6073
# generate a data.frame of fake data to match your problem
C <- 12
R <- 100
data <- matrix(sample(1:9, size=C*R, replace=TRUE), nrow=R, ncol=C)
df <- as.data.frame(data)
names(df) <- paste0("change_",1:C)
# create a new variable
df$newvar = 0
# replace each row of newvar with a 1 if
# the value for change_i is 1, 6, or 9
for(i in 1:C) {
who_to_replace <- df[[paste0("change_",i)]] %in% c(1,6,9)
df[who_to_replace, "newvar"] <- 1
}
Upvotes: 2