【问题标题】:Convert embraced {{}} data variable to character将包含的 {{}} 数据变量转换为字符
【发布时间】:2021-02-22 23:25:34
【问题描述】:

我一直在研究一个涉及整洁评估的问题,诚然,我对此很陌生。我有一个简单的函数,它使用 dplyrtidyr 中的 summarizepivot_wider 制作列联表,但我无法将它从 小标题:

library(tidyverse)

#Function to produce contingency table

countTable1 <- function(d,col1,col2){ #This function works correctly
  d %>% group_by({{col1}},{{col2}}) %>% summarize(n=n()) %>%
    pivot_wider(names_from={{col1}},values_from=n,values_fill=0)  
}

countTable2 <- function(d,col1,col2){ #This function fails
  d %>% group_by({{col1}},{{col2}}) %>% summarize(n=n()) %>%
    pivot_wider(names_from={{col1}},values_from=n,values_fill=0) %>% 
    column_to_rownames(var = as_label({{col2}})) #Should change col2 variable to rownames
}

这是一个测试数据集:

> #Test data
> d <- data.frame(c1=sample(letters[1:5],30,TRUE),c2=sample(letters[6:8],30,TRUE))
> countTable1(d,c1,c2) #Contingency table is fine, but c2 needs to be the rowname

# A tibble: 3 x 6
  c2        a     b     c     d     e
  <fct> <int> <int> <int> <int> <int>
1 f         3     3     2     1     2
2 g         4     0     3     2     4
3 h         0     2     0     2     2

> countTable1(d,c1,c2) %>% #Should behave like this:
+   column_to_rownames(var = 'c2')

  a b c d e
f 3 3 2 1 2
g 4 0 3 2 4
h 0 2 0 2 2

> countTable2(d,c1,c2) #This function fails
 Error in is_quosure(quo) : object 'c2' not found 

将数据变量转换为数据变量名称的正确方法是什么? 显然,双括号 "curly-curly" 运算符没有按照我的意愿进行操作。我找不到任何关于此hereherehere 的信息,但我认为我走在正确的轨道上。

【问题讨论】:

    标签: r dplyr tidyr rlang


    【解决方案1】:

    在这种情况下,您最好明确地使用enquo 来处理您需要作为quosures 和字符串值的变量。你可以这样做

    countTable2 <- function(d,col1,col2){ #This function fails
      col2 <- enquo(col2)
      d %>% group_by({{col1}},{{col2}}) %>% summarize(n=n()) %>%
        pivot_wider(names_from={{col1}}, values_from=n, values_fill=0) %>% 
        column_to_rownames(var = as_label(col2)) 
    }
    

    【讨论】:

      【解决方案2】:

      column_to_rownames 需要字符串输入。一种方法是使用deparse + substitute

      我也将group_by + summarise(n()) 更改为count

      library(dplyr)
      
      countTable2 <- function(d,col1,col2){ 
      
        col <- deparse(substitute(col2))
        d %>% 
          count({{col1}},{{col2}}) %>% 
          pivot_wider(names_from={{col1}},values_from=n,values_fill=0) %>%
          column_to_rownames(col) #Should change col2 variable to rownames
      }
      
      countTable2(d,c1,c2)
      #  a b c d e
      #f 5 3 2 0 4
      #g 2 1 2 2 4
      #h 0 4 0 0 1
      

      【讨论】:

      • 这个解决方案有效,但我发现了另一个奇怪的怪癖:如果你尝试在函数内部使用deparse(substitute(x)) 而不是像这里那样将它变成一个额外的变量,这可能会导致问题。希望这对某人有用!
      猜你喜欢
      • 2022-10-14
      • 1970-01-01
      • 1970-01-01
      • 2014-10-30
      • 2013-12-23
      • 1970-01-01
      • 2018-04-08
      • 2019-01-21
      • 1970-01-01
      相关资源
      最近更新 更多