R语言循环生成缺失值哑变量报错求助(Stata转R新手)
Hey there! As someone making the switch from Stata to R, it's totally normal to hit small syntax snags—let's get your loop working correctly so you can generate those missing value dummy variables.
Why Your Current Code Throws Warnings
Your warnings stem from two key syntax mistakes in how R handles dynamic column names:
reflex_working$i: R interprets this as a literal column namedi, not the variable name stored in your loop iteratori. Since your data frame doesn't have a column calledi, you get the "unknown column" warning.reflex_working$miss_[i]: This syntax is invalid for creating dynamic column names. You need to combine the prefixmiss_with the original variable name to form the new column's proper name.
Corrected Loop Code
Here's the fixed version of your loop that will generate the miss_变量名 columns exactly as you want:
varlist <- c("A7LECTUR", "A7GROASG", "A7RESPRJ", "A7WORPLC", "A7PRACTI", "A7THEORI", "A7TEACHR", "A7PROBAL", "A7WRIASG", "A7ORALPR") for (i in varlist) { # Create the new variable name by combining "miss_" with the original variable name new_var_name <- paste0("miss_", i) # Use [[ ]] to dynamically reference columns and assign the dummy variable reflex_working[[new_var_name]] <- ifelse(reflex_working[[i]] == -9, 1, 0) }
How It Works
paste0("miss_", i)builds the exact new column name you need (e.g.,miss_A7LECTURwheniis"A7LECTUR").reflex_working[[i]]tells R to pull the column whose name is stored in the variablei(instead of looking for a column literally namedi).- The
ifelse()statement checks if the original value is-9and assigns1if true,0otherwise—exactly matching your requirement.
Bonus: A Tidyverse Alternative (More Stata-like Syntax Feel)
If you're open to using the dplyr package (part of the tidyverse, which has syntax that might feel more intuitive for Stata users), you can do this in one line without a loop:
library(dplyr) reflex_working <- reflex_working %>% mutate(across(all_of(varlist), ~ifelse(.x == -9, 1, 0), .names = "miss_{.col}"))
across(all_of(varlist))tells R to apply the following operation to every variable invarlist.~ifelse(.x == -9, 1, 0)is the operation: check each value ((.x)refers to the current variable) and assign the dummy value..names = "miss_{.col}"automatically generates the new column names, replacing{.col}with the original variable name.
Both methods will produce the result you want: for an original variable A7LECTUR with values [1,2,1,4,-9], you'll get a miss_A7LECTUR column with values [0,0,0,0,1].
内容的提问来源于stack exchange,提问作者Gabriele Dente

