问题描述
我有这个数据框:
#create reprex data
tested_data <- tibble(STYL1 = c(1,2,3,1,2),STYL2 = c(2,4),STYL3 = c(4,4,3))
我想要STYL1的每个数字都有行数,我这样做是:
tested_data %>%
group_by(STYL1) %>%
count() %>%
ungroup()
它运行完美,我有这个:
# A tibble: 3 x 2
STYL1 n
<dbl> <int>
1 1 2
2 2 2
3 3 1
但是我想为每个STYL ...变量添加一个for循环,这样(我想用openxlsx包在一个Excel工作簿中一个接一个地添加每个数据帧):
list <- c("STYL1","STYL2","STYL3")
for (tempo_variable in list) {
dt <- tested_data %>%
group_by(tempo_variable) %>%
count() %>%
ungroup()
}
进行一个循环对我很重要,因为我不知道我将拥有多少个STYL ...变量,我必须为每个STYL ...变量执行此任务。 有人知道如何执行此操作吗?也许我不必使用for循环? 请帮助我!
解决方法
也许尝试这样的事情?
lapply(c("STYL1","STYL2","STYL3"),function(x,df) df %>% group_by(across(!!x)) %>% count() %>% ungroup(),tested_data)
,
您可以使用tidyr::pivot_longer
整理数据,然后按输出中的两列进行分组。
library(tidyverse)
tested_data <- tibble(STYL1 = c(1,2,3,1,2),STYL2 = c(2,4),STYL3 = c(4,4,3))
tested_data %>%
pivot_longer(everything(),names_to = "STYL",values_to = "values") %>%
group_by(STYL,values) %>%
count()
#> # A tibble: 11 x 3
#> # Groups: STYL,values [11]
#> STYL values n
#> <chr> <dbl> <int>
#> 1 STYL1 1 2
#> 2 STYL1 2 2
#> 3 STYL1 3 1
#> 4 STYL2 1 1
#> 5 STYL2 2 2
#> 6 STYL2 3 1
#> 7 STYL2 4 1
#> 8 STYL3 1 1
#> 9 STYL3 2 1
#> 10 STYL3 3 1
#> 11 STYL3 4 2
由reprex package(v0.3.0)于2020-10-19创建