如何根据 R 中另一个变量的值更改变量中的值?

How do I change a value within a variable based on the value of another variable in R?

我正在尝试重新编码人口统计变量。如果变量Q36等于Other,变量Q35等于Yes,我想把Other(从Q36)改成Hispanic。如果变量Q36等于Other,变量Q35等于No,我想把Other(从Q36)改成Unspecified.

到目前为止,这是我的代码。

data %>% 
  mutate(Q36 = case_when(Q35 == "Yes" & Q36 == "Other" ~ Q36 == "Hispanic", 
Q35 == "No" & Q36 == "Other" ~ Q36 == "Unspecified")) -> data

你很接近:

data %>% 
  mutate(Q36 = case_when(Q35 == "Yes" & Q36 == "Other" ~ "Hispanic", 
                 Q35 == "No" & Q36 == "Other" ~ "Unspecified",
                TRUE~Q36))