我正在尝试编写一个清除变量的函数,将“*”替换为“1”,将NA替换为“0”。我可以用ifelse轻松地做到这一点,但我希望它干净并使用函数式编程,但我显然不在那里......
示例数据库是:
db <- data.frame(
name = c("Abel", "Abner", "Bianca", "Pedro", "Lucas"),
scholarship1 = c("*", "*", "*", "*", NA),
scholarship2 = c("*", NA, NA, "*", "*"))
)
我的功能是这样的:
Dichotomizer <- function(database, variable) {
variable <- enquo(variable)
database$variable <- ifelse(
is.na(database$variable),
0,
1
)
}
但它显然不起作用,我无法找出原因......我尝试使用eval和替代品,但它仍然会导致错误。
我感谢任何解决我问题的输入。感谢。
答案 0 :(得分:0)
由于您的示例函数是属性属性,因此以下是一个工作示例:
db <- data.frame(
name = c("a", "b", "c", "d", "e"),
scholarship1 = c("*", "*", "*", "*", NA),
scholarship2 = c("*", NA, NA, "*", "*"))
dichotomizer <- function(database, variable) {
copy <- rep(0, nrow(database[variable]))
copy[which(database[variable] == "*")] = 1
database[variable] <- copy
return(database)
}
new_db <- dichotomizer(db, "scholarship1")
final_db <- dichotomizer(new_db, "scholarship2")