R:使用匿名函数创建虚拟变量

R: Using an anonymous function to create dummy variables

假设您有一个包含分类变量的数据集,并且您想将其转换为虚拟变量:

df<-data.frame(read.table(header = TRUE, text = 
"ID Mobile
1 Yes
2 No
3 Yes
4 Yes
5 No"))

我通常会这样做:

for(level in levels(df$Mobile)){
df[paste("Mobile", level, sep = "_")] <- ifelse(df$Mobile == level, 1,   0)
}

这很好用。但是,现在假设您有许多这样的分类变量。您不想多次复制和粘贴这三行代码,而是想使用匿名函数。我试过如下:

Mediatable<-function(VARIABLE1, DUMMY1, INDICATOR1){
   for(level in levels(VARIABLE1)){
      df[paste(DUMMY1, level, sep = "_")] <- ifelse(VARIABLE1 == level, 1, 0)
   }
}

然后我会按如下方式触发它:

Mediatable(df$Mobile, "Mobile") 

我试过了,没有任何反应。知道出了什么问题吗?我真的很喜欢使用匿名函数来跨多个分类变量完成这项工作的想法。顺便说一句,请忽略我想通过粘贴为我的虚拟变量分配一个特定的名称。这在这里无关紧要。谢谢!

在您的函数中添加一个 return(df) 调用。或者使用 reshape2 中的 dcast 作为另一种方法:

library(reshape2)
dcast(df, ...~Mobile, length)
#   ID No Yes
# 1  1  0   1
# 2  2  1   0
# 3  3  0   1
# 4  4  0   1
# 5  5  1   0

用你的函数:

Mediatable<-function(VARIABLE1, DUMMY1, INDICATOR1){
        for(level in levels(VARIABLE1)){
                df[paste(DUMMY1, level, sep = "_")] <- ifelse(VARIABLE1 == level, 1, 0)
        }
        return(df)
}

newdf <- Mediatable(df$Mobile, "Mobile") 
newdf
#   ID Mobile Mobile_No Mobile_Yes
# 1  1    Yes         0          1
# 2  2     No         1          0
# 3  3    Yes         0          1
# 4  4    Yes         0          1
# 5  5     No         1          0