我正在try 使用sApply和Switch将描述性名称应用于数据.我已经多次使用这种方法,没有出现问题,但在我最近的项目中(只有一个!)专栏,它抛出了一个错误.我最好的猜测是,即使值被保存为字符串,否则该值将是R中的保留字.我在下面创建了一个可重现的示例.
我的项目中的实际价值与性别无关,可能有许多可能的 Select .谁能告诉我如何使用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" = "F - female", "M" = "M - male")
我收到的错误是"Error in Get(as.Character(Fun),MODE="Function",envir=envir): 找不到模式‘Function’的对象‘F-Female’."