有没有办法为多重变量制作一个虚拟变量?试图拥有"White" |"White British" | "White Other"为 1,其他任何值为 0



我试过了;

new_data $Ethnicity_dummy = as.numeric(new_data$Ethnicity == "White"|"White British"| "White Other")

但是我得到这个错误信息;

new_data $Ethnicity_dummy = as.numeric(new_data$Ethnicity == "White"|"White British"| "White Other")
Error in new_data$Ethnicity == "White" | "White British" : 
operations are possible only for numeric, logical or complex types

您正在使用"或"(|)函数不正确-如果您想使用or符号,则必须每次指定变量(即new_data$Ethnicity == "White"|new_data$Ethnicity =="White British"...)

一个更简单的方法是%in%-尝试使用:

new_data$Ethnicity_dummy = as.numeric(new_data$Ethnicity %in% c("White","White British","White Other"))

最新更新