将Stata Forvalues循环转换为R

时间:2018-07-25 16:02:31

标签: r loops stata

我想对一系列变量(从Change_1到Change_12)进行循环,以检查它们是否满足某些条件。基于此,我想创建假人。如何在R中执行此循环?

 generate newvariable=0
 forvalues i = 1/12 {  
 replace newvariable=1 if Change_`i'==1 | Change_`i'== 6| Change_`i'==9
    }

1 个答案:

答案 0 :(得分:2)

# 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
}