在for循环中转换tibble

transform tibble in a for loop

我有这个数据框:

#create reprex data
tested_data <- tibble(STYL1 = c(1,2,3,1,2), STYL2 = c(2,2,3,1,4), STYL3 = c(4,2,4,1,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

但我想添加一个 for 循环来为每个 STYL... 变量做这个(我想在 excel 工作簿中添加每个数据框,每个数据框都带有 openxlsx 包):

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,2,3,1,4), STYL3 = c(4,2,4,1,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 创建