【发布时间】:2021-02-22 23:25:34
【问题描述】:
我一直在研究一个涉及整洁评估的问题,诚然,我对此很陌生。我有一个简单的函数,它使用 dplyr 和 tidyr 中的 summarize 和 pivot_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" 运算符没有按照我的意愿进行操作。我找不到任何关于此here、here 或here 的信息,但我认为我走在正确的轨道上。
【问题讨论】: