【问题标题】:dplyr rename "object not found" [closed]dplyr 重命名“找不到对象”[关闭]
【发布时间】:2019-05-22 04:06:11
【问题描述】:

当我尝试重命名 dplyr 中的多个列时,我收到关于新名称的“找不到对象”错误。

我正在使用 select 创建一个新数据框,然后我想更改 4:8 列的名称。

commute_mode<-select(commute,geoid,GEO.id2,display_label,HD01_VD26,HD01_VD37,HD01_VD68,HD01_VD113,HD01_VD125) %>%
  rename(HD01_VD26 = drive, HD01_VD37 = carpool,HD01_VD68 = public_trans,HD01_VD113 = walk, HD01_VD125=bike_other)

但我得到了

Error in .f(.x[[i]], ...) : object 'drive' not found

【问题讨论】:

  • 交换重命名顺序,新名称=当前。 drive = HD01_VD26
  • 您需要输入drive = HD01_VD26 而不是HD01_VD26 = drive。这里调用rename也是多余的,你可以简单地重命名select里面的变量。
  • 我在这里发表评论是因为问题已关闭,但是当您加载了多个具有不同rename 函数的包时,经常会出现此错误;使用dplyr::rename 函数修复神秘错误。

标签: r dplyr rename


【解决方案1】:

正如一些 cmets 中所指出的,变量的新旧名称需要在您的 select() 函数中交换。

但也如前所述,您可以选择并使用select() 重命名变量(如果您保留所有列并仅重命名某些列,则rename() 是最好的)。因此,您只需拥有mydata %&gt;% select(new_var1 = old_var1, new_var2 = old_var2),而不是笨重的mydata %&gt;% select(old_var1, old_var2) %&gt;% rename (new_var1 = old_var1, new_var2 = old_var2)。在你的情况下,这看起来像:

commute_mode <- commute %>% select(geoid, GEO.id2, display_label,
                                   drive = HD01_VD26, carpool = HD01_VD37,
                                   public_trans = HD01_VD68,
                                   walk = HD01_VD113,
                                   bike_other = HD01_VD125)

这是select() 命令的一个很棒的功能,并且总是尽可能的简洁!

更详细的解释可以查看https://dplyr.tidyverse.org/reference/select.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 2021-11-19
    • 2021-10-30
    • 2017-04-10
    • 2021-04-10
    • 2016-11-26
    相关资源
    最近更新 更多