首页 > 解决方案 > 使用 dplyr 和循环创建多个数据,计算每个变量的唯一值

问题描述

我对使用 dplyr 和 for 循环进行编程以创建多个数据有一些疑问。没有循环的代码效果很好,但是带有 for 循环的代码并没有给我预期的结果以及错误消息。

错误消息如下:

“UseMethod(“select_”)中的错误:没有适用于“select_”的方法应用于“字符”类的对象

请任何人让我走上正确的道路。

下面的代码有效

B <- data %>% select (column1) %>% group_by (column1) %>% arrange (column1) %>% summarise (n = n ())

下面的代码不起作用

column_list <- c ('column1', 'column2', 'column3')

for (b in column_list) {

 a <- data %>% select (b) %>% group_by (b) %>% arrange (b) %>% summarise (n = n () )
 assign (paste0(b), a)
}

标签: rdplyr

解决方案


Don't use assign. Instead use lists.

We can use _at variations in dplyr which works with characters variables.

library(dplyr)

split_fun <- function(df, col) {
  df %>% group_by_at(col) %>% summarise(n = n()) %>% arrange_at(col)
}

and then use lapply/map to apply it to different columns

purrr::map(column_list, ~split_fun(data, .))

This will return you a list of dataframes which can be accessed using [[ individually if needed.


Using example with mtcars

df <- mtcars
column_list <- c ('cyl', 'gear', 'carb')

purrr::map(column_list, ~split_fun(df, .))

#[[1]]
# A tibble: 3 x 2
#    cyl     n
#  <dbl> <int>
#1     4    11
#2     6     7
#3     8    14

#[[2]]
# A tibble: 3 x 2
#   gear     n
#  <dbl> <int>
#1     3    15
#2     4    12
#3     5     5

#[[3]]
# A tibble: 6 x 2
#   carb     n
#  <dbl> <int>
#1     1     7
#2     2    10
#3     3     3
#4     4    10
#5     6     1
#6     8     1

推荐阅读