【问题标题】:Can I use a character vector with recode() and mutate()我可以使用带有 recode() 和 mutate() 的字符向量吗
【发布时间】:2018-06-08 13:51:11
【问题描述】:

我有一个如下图所示的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 

我可以使用 recode() 和 mutate() 添加一个额外的列,基于 $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 = "Higher/Secondary Education Establishment"' 开头的列表?

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

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 中过度设计我对重新编码的使用?您能否建议在重新编码中输入每条指令的替代方法?当涉及到使用许多单独的指令重新编码时,代码开始变得非常冗长和笨拙!

【问题讨论】:

  • 请用dput提供一个可重复的小例子
  • 嗨 @akrun 我希望我的 tbl 的这个精简的 head() 可以吗?我仍然不确定如何正确使用 dput()

标签: r character dplyr recode


【解决方案1】:

不要创建向量,而是使用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))

【讨论】:

  • 这很好用@akrun 谢谢。为了学习,你能解释一下为什么我们需要使用'!!!'吗?我在文献或堆栈中的任何地方都没有看到这种方法。
  • @geofffest 这是一个 bang bang bang 运算符,用于根据函数采用的参数在有多组表达式时进行评估。您可以查看here了解更多信息
猜你喜欢
  • 2019-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多