dplyr中recode()函数报错‘Argument 2 must be named’求助
解决dplyr::recode()的"Argument 2 must be named"报错
你当前的错误是因为dplyr的recode函数不支持把所有映射写在单个字符串里,这种写法是其他包(比如car包的recode)的语法,而dplyr要求用命名参数或命名向量来指定值的映射规则。
修正方案1:使用命名参数
直接将每个映射作为独立的命名参数传入,用逗号分隔,同时把else=NA替换为dplyr支持的.default=NA:
protestag <- recode( Event..legacy..see.tags., 'Education' = 1, 'Executive' = 2, 'Immigration' = 3, 'Racial Injustice' = 4, 'Collective Bargaining' = 5, 'Civil Rights' = 6, 'Healthcare' = 7, .default = NA, as.factor = FALSE )
修正方案2:使用命名向量
先定义一个命名向量存储映射关系,再传入recode函数,这种方式适合映射规则较多的场景:
tag_mapping <- c( 'Education' = 1, 'Executive' = 2, 'Immigration' = 3, 'Racial Injustice' = 4, 'Collective Bargaining' = 5, 'Civil Rights' = 6, 'Healthcare' = 7 ) protestag <- recode( Event..legacy..see.tags., !!!tag_mapping, # 用!!!展开命名向量 .default = NA, as.factor = FALSE )
关键注意点
- dplyr的recode不支持分号分隔的字符串映射,必须用命名参数或命名向量
- 兜底的默认值要用
.default参数,而不是else=NA
内容的提问来源于stack exchange,提问作者Aly
相关产品推荐
相关产品推荐

