【问题标题】:R: How to change name of table when using get()R:使用 get() 时如何更改表名
【发布时间】:2018-02-08 02:33:51
【问题描述】:

我正在尝试获取按两个变量分组的一系列记录总和:列“a”,然后是数据集中的其余列。

当我在下面运行时:

vars <- c(colnames(df))
vars<-vars[-1]

counting<-function(index) {
  count(df,a,get(index))
}

vars[]<-lapply(vars,FUN=counting)

get(index) 生成的列的名称在我的列表变量中命名为“get(index)”。如何更改它以使输出中的列名与原始列名相同?

例如,(这个数据框是根据datacamp中的教程修改的),如果我有这个数据框:

First.Name <- c("John", "Edgar", "Walt", "Jane")
Second.Name <- c("Doe", "Poe", "Whitman", "Austen")
Sex <- c("MALE", "MALE", "MALE", "FEMALE")
writers_df <- data.frame(First.Name, Second.Name, Sex)

我想计算有多少行具有 Sex 和其他变量的唯一组合,我会运行:

vars <- c(colnames(writers_df))
vars<-vars[-3]
counting<-function(index) {
  count(df,Sex,get(index))
}

vars[]<-lapply(vars,FUN=counting)

其中一张表的输出将如下所示:

Sex get(index) n
M   John       1
M   Edgar      1
M   Walt       1
F   Jane       1

如何在不“手动”手动更改的情况下获取名为 First.Name 的列 get(index)?

【问题讨论】:

    标签: r function


    【解决方案1】:

    使用下划线版本:count_:

    counting <- function(index) {
      count_(writers_df, c('Sex', index))
    }
    
    > lapply(vars,FUN=counting)
    [[1]]
    # A tibble: 4 x 3
      Sex    First.Name     n
      <fct>  <fct>      <int>
    1 FEMALE Jane           1
    2 MALE   Edgar          1
    3 MALE   John           1
    4 MALE   Walt           1
    
    [[2]]
    # A tibble: 4 x 3
      Sex    Second.Name     n
      <fct>  <fct>       <int>
    1 FEMALE Austen          1
    2 MALE   Doe             1
    3 MALE   Poe             1
    4 MALE   Whitman         1
    
    [[3]]
    # A tibble: 2 x 2
      Sex        n
      <fct>  <int>
    1 FEMALE     1
    2 MALE       3
    

    【讨论】:

    • @crayfishcray 这个答案完全没问题,请注意 count_ 和其他下划线版本已被弃用,因此它们可能会从 dplyr 的未来版本中删除。
    • @joran 你是对的,虽然我认为那将是一种耻辱。我一直认为下划线版本更符合 tidyverse 的理念:可读代码 + 一个功能,一个目的。
    【解决方案2】:

    试试这个:

    counting<-function(var) {
      count(writers_df,Sex,!!rlang::sym(var))
    }
    
    > lapply(vars,counting)
    
    [[1]]
    # A tibble: 4 x 3
         Sex First.Name     n
      <fctr>     <fctr> <int>
    1 FEMALE       Jane     1
    2   MALE      Edgar     1
    3   MALE       John     1
    4   MALE       Walt     1
    
    [[2]]
    # A tibble: 4 x 3
         Sex Second.Name     n
      <fctr>      <fctr> <int>
    1 FEMALE      Austen     1
    2   MALE         Doe     1
    3   MALE         Poe     1
    4   MALE     Whitman     1
    

    【讨论】:

      猜你喜欢
      • 2013-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      相关资源
      最近更新 更多