我可以使用带有recode()和mutate()的字符向量吗?

时间:2018-06-08 13:51:11

标签: r dplyr character mutate recode

我有一个如下所示的tbl:

   # A tibble: 6 x 8
  projectRcn projectID projectAcronym role        id name   shortName activityType
       <int>     <int> <chr>          <chr>    <int> <chr>  <chr>     <chr>       
1     208327    741617 PROSME-INN     parti~  9.44e8 INSTI~ INMA Buc~ PUB         
2     208327    741617 PROSME-INN     parti~  9.39e8 CAMER~ CCIPH     OTH         
3     208327    741617 PROSME-INN     parti~ 10.00e8 FUNDA~ CRIMM     OTH         
4     208327    741617 PROSME-INN     coord~  9.41e8 AGENT~ ADRSM     OTH         
5     208327    741617 PROSME-INN     parti~  9.41e8 SC IN~ SC INPUL~ PRC         
6     208327    741617 PROSME-INN     parti~  9.54e8 AGENT~ ADRBI     PUB 

我可以使用带有mutate()的recode()来添加一个额外的列,基于$ activityType,使用下面的代码调用$ orgType:

h2020orgs <- mutate(h2020orgs,
                    orgType = recode(activityType,
                          HES = "Higher/Secondary Education Establishment",
                          OTH = "Other",
                          PRC = "Private/For-profit entity",
                          PUB = "Public body",
                          REC = "Research Organisation"))

有没有办法在'activityType'之后用'HES ='高等/中等教育机构''替换以单个向量开头的列表?

我尝试过定义一个字符向量......

cordisActivityTypes <- c(HES = "Higher/Secondary Education Establishment",
                         OTH = "Other",
                         PRC = "Private/For-profit entity",
                         PUB = "Public body",
                         REC = "Research Organisation")

...然后使用它代替单独输入的字符串:

h2020orgs <- mutate(h2020orgs,
                    orgType = recode(activityType,
                                     as.character(cordisActivityTypes)))

这会引发以下错误:

Error in mutate_impl(.data, dots) : 
  Evaluation error: Argument 2 must be named, not unnamed.

我是否试图过度设计我在mutate中使用recode?您能否建议在重新编码中键入每个单独的指令?当涉及到使用许多单独指令进行重新编码时,代码开始变得非常冗长且难以处理!

1 个答案:

答案 0 :(得分:2)

使用list

而不是创建矢量
cordisActivityTypes <- list(HES = "Higher/Secondary Education Establishment",
                     OTH = "Other",
                     PRC = "Private/For-profit entity",
                     PUB = "Public body",
                     REC = "Research Organisation")

然后使用!!!

进行评估
h2020orgs %>%
             mutate(orgType = recode(activityType, !!! cordisActivityTypes))