我正在尝试使用 sapply 和 switch 将描述性名称应用于数据。我已经多次使用这种方法,没有出现任何问题,但对于我最近的项目中的(只有一个!)专栏,它抛出了错误。我最好的猜测是,即使该值保存为字符串,该值也将是 R 中的保留字。我在下面创建了一个可重现的示例。
我的项目中的实际值与性别无关,并且可能有许多可能的选择。有人可以告诉我如何使用 sapply/switch 来避免代码中出现许多嵌套的 ifelse 语句吗?
# create test data
testdta <- as.data.frame(cbind(userid = c("1", "2", "3", "4"), gender = c("F", "M", "F", "M")))
# sapply/switch works with strings that are not reserved words
testdta$uiddescription <- sapply(testdta$userid, switch, "1" = "1 - first", "2" = "2 - second", "3+ - third or beyond")
testdta
# sapply/switch won't work when trying to interpret gender (possibly because F is reserved?)
testdta$gdescription <- sapply(testdta$gender, switch, "F" = …Run Code Online (Sandbox Code Playgroud)