【问题标题】:Select columns and group by columns in function arguments在函数参数中选择列并按列分组
【发布时间】:2019-11-27 23:16:37
【问题描述】:

我正在尝试编写一个函数,以便我可以输入要在整体级别和分组变量中描述的任何列。

但是,我无法获得分组结果的输出。

我的数据:

df <- data.frame(gender=c("m", "f", "m","m"), age=c("18-22","23-32","23-32","50-60"), income=c("low", "low", "medium", "high"), group=c("A", "A", "B", "B"))
> df
  gender   age income group
1      m 18-22    low     A
2      f 23-32    low     A
3      m 23-32 medium     B
4      m 50-60   high     B

功能:

library(dplyr)
make_sum <- function(data=df, cols, group_var) {
data %>% dplyr::select(cols)  %>%
  # print tables with frequency and proportions
  apply(2, function(x) {
    n <-  table(x, useNA = "no")
    prop=round(n/length(x[!is.na(x)])*100,2)
    print(cbind(n, prop)) 
  })
  # print tables by group
data %>% dplyr::select(cols, vars(group_var))  %>%
  apply(2, function(x) {
    n <-  table(x, vars(group_var),useNA = "no")
   print(n)
  })  
}

cols <- df %>% dplyr::select(gender,age, income) %>% names()

make_sum(data=df, cols=cols, group_var="group")

我得到了整个表格的正确输出,但没有分组,显示此错误:

Error: `vars(group_var)` must evaluate to column positions or names, not a list

分组性别变量的期望输出(示例):

    A B
  f 1 0
  m 1 2

【问题讨论】:

  • vars 包装器在 tidyverse 函数中工作,您在 base R 上调用它

标签: r


【解决方案1】:

可以在这里调用summarise_all,而不是使用applyMARGIN = 2。此外,vars 包装与 tidyverse 函数一起应用。在这里,为了获得频率,一个选项是使用更直接的[[ 对列进行子集化。此外,由于summarise 仅返回一行(对于每个组 - 如果有分组变量),我们可以将输出包装在 list

make_sum <- function(data=df, cols, group_var) {
data %>% 
  dplyr::select(cols)  %>%
   summarise_all(~ {

    n <-  table(.,  data[[group_var]], useNA = "no")
    #list(round(n/length(.[!is.na(.)])*100,2))
    list(n)

  })
  }


cols <- df %>%
            dplyr::select(gender,age, income) %>%
            names()

out <- make_sum(data=df, cols=cols, group_var="group")
out$gender
#[[1]]

#.   A B
#  f 1 0
#  m 1 2

【讨论】:

  • 这很好用。我将函数修改如下以在同一个表中打印比例(按列): make_sum % dplyr::select(cols) %>% summarise_all(~ { n
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多