小编hua*_*uan的帖子

用函数替换多个`summaryize`语句

我目前正在重复很多代码,因为summarize对于不同的组,我需要始终使用相同的列。如何通过只编写一次summarize函数(始终相同)来有效地做到这一点,但是要group_by逐个定义输出名称和参数?

一个最小的例子:

col1 <- c("UK", "US", "UK", "US")
col2 <- c("Tech", "Social", "Social", "Tech")
col3 <- c("0-5years", "6-10years", "0-5years", "0-5years")
col4 <- 1:4
col5 <- 5:8

df <- data.frame(col1, col2, col3, col4, col5)

result1 <- df %>% 
  group_by(col1, col2) %>% 
  summarize(sum1 = sum(col4, col5))

result2 <- df %>% 
  group_by(col2, col3) %>% 
  summarize(sum1 = sum(col4, col5))

result3 <- df %>% 
  group_by(col1, col3) %>% 
  summarize(sum1 = sum(col4, col5))
Run Code Online (Sandbox Code Playgroud)

r function summarize tidyverse

4
推荐指数
1
解决办法
81
查看次数

标签 统计

function ×1

r ×1

summarize ×1

tidyverse ×1