r - 使用 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)
}
解决方案
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
推荐阅读
- wordpress - woocommerce 产品属性无法以编程方式工作
- string - 在给定无限数量的 0 和 1 的情况下,找出可以形成大小为 N 的字符串的方法数
- r - R 带有 KPI 标题的闪亮选项卡选项卡
- c++ - lambda 函数是否需要任何头文件?
- javascript - 渲染分页中的 OnPageChange 在页面加载中调用 handlePageClick
- php - 使用 PHP MySql 加入表
- arrays - 如果数组中存在用户输入编号,我试图获取元素的索引。但是当给出输入时,我得到与输出相同的数字
- vue.js - 在 vue.js 中使用 agora.io
- angular - 显示数据时未定义
- html - 绝对定位的 div 覆盖了我的内容