如何在R语言中从5级变量生成多个3级变量并保留原变量
Got it, let's solve this problem! You want to retain your original 5-level variables while generating new 3-level variables with the _3l suffix—mirroring the behavior of Stata's recode ... gen(...) command. Here's a clean, modern R implementation using dplyr:
Step 1: Reproduce Your Data
First, let's recreate your original dataset to work with:
library(dplyr) # Original 5-level data df <- structure( list( Question1 = c("I", "5", "4", "4"), Question2 = c("I", "5", "4", "4"), Question3 = c("I", "3", "2", "4") ), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -4L) )
Step 2: Generate New 3-Level Variables (Keep Originals)
Use mutate(across(...)) (the updated replacement for mutate_at) to batch-process your variables, recode them, and create new columns without overwriting the originals:
df_updated <- df %>% mutate( # Target the variables you want to recode across( c(Question1, Question2, Question3), # Define your recoding rules (matches your Stata logic) ~recode( ., '1' = '1', '2' = '1', # 5-level 1/2 → 3-level 1 '3' = '2', # 5-level 3 → 3-level 2 '4' = '3', '5' = '3', # 5-level 4/5 → 3-level 3 'I' = NA_character_ # 'I' maps to NA ), # Auto-name new columns with _3l suffix .names = "{col}_3l" ) )
Step 3: Verify the Result
When you print df_updated, you'll get exactly the structure you're looking for:
print(df_updated)
Output:
# A tibble: 4 × 6 Question1 Question2 Question3 Question1_3l Question2_3l Question3_3l <chr> <chr> <chr> <chr> <chr> <chr> 1 I I I NA NA NA 2 5 5 3 3 3 2 3 4 4 2 3 3 1 4 4 4 4 3 3 3
Bonus: Batch-Process Variables by Pattern
If you have many variables to recode (like Stata's varlist range), you can use a pattern match instead of listing each variable. For example, if all target variables start with "Question":
df_updated <- df %>% mutate( across( starts_with("Question"), ~recode(., '1'='1', '2'='1', '3'='2', '4'='3', '5'='3', 'I'=NA_character_), .names = "{col}_3l" ) )
This approach keeps your original data intact while efficiently generating the new 3-level variables you need.
内容的提问来源于stack exchange,提问作者JohnD

