【问题标题】:Change column names using *plyr where the mapping is given by two columns of another data frame使用 *plyr 更改列名,其中映射由另一个数据框的两列给出
【发布时间】:2020-02-17 23:33:51
【问题描述】:

我有一个简单的数据框a

  x  y
1 1 11
2 2 22
3 3 33

还有一个b

  old  new
1   x haha
2   y hoho

它给出了旧列名到新列名的映射。我想要以下数据框c

  haha hoho
1    1   11
2    2   22
3    3   33

请注意,实际的a 有很多列,b 中的两列的映射不是直截了当的。此外,b 的行可能不a 的列的顺序相同。

可以使用plyr/dplyr吗?在 python 中是这样的:Changing dataframe columns names by columns from another dataframe python?

【问题讨论】:

    标签: r dplyr tidyr plyr


    【解决方案1】:

    这是使用!!的绝佳机会:

    library(tidyverse)
    
    data <- tribble(
      ~x, ~y,
      1,  11,
      2,  22,
      3,  33
    )
    
    name_tbl <- tribble(
      ~old, ~new,
      "x",  "haha",
      "y",  "hoho"
    )
    
    (name_pairs <- with(name_tbl, set_names(old, new)))
    #> haha hoho 
    #>  "x"  "y"
    
    rename(data, !!name_pairs)
    #> # A tibble: 3 x 2
    #>    haha  hoho
    #>   <dbl> <dbl>
    #> 1     1    11
    #> 2     2    22
    #> 3     3    33
    

    reprex package (v0.3.0) 于 2019 年 10 月 21 日创建

    rename() 使用名称-值对(以新名称作为名称),所以我们只需要 1)获取旧名称的向量,2)给它新名称的名称,以及 3)调用rename() 带有命名向量,未加引号,因为我们将这些对作为对象值而不是语法传递。

    【讨论】:

    • 谢谢@DHW。 tidyverse 函数的文档中没有提到这些简单的技巧。我知道它一定与命名向量有关。但是rename 的描述并没有提到你可以传递一个命名向量。
    • 描述不正确,但可以在其中一个参数中找到:The arguments in ... are automatically quoted and evaluated in a context where column names represent column positions. They also support unquoting and splicing. See vignette("programming") for an introduction to these concepts. 查看最后一个示例,也可以:# For convenience it also supports strings and character # vectors. This is unlike other verbs where strings would be # ambiguous. vars &lt;- c(var1 = "cyl", var2 ="am") select(mtcars, !!vars) rename(mtcars, !!vars)
    猜你喜欢
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    相关资源
    最近更新 更多