[英]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)
調用。 或者使用dcast
的reshape2
進行另一種方法:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.