transform tibble in a for loop

60 Views Asked by At

i have this dataframe :

#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))

And i want to have the number of rows for each number for STYL1 and i do this :

tested_data %>% 
  group_by(STYL1) %>% 
  count() %>% 
  ungroup()

and it works perfectly, i have this :

# A tibble: 3 x 2
  STYL1     n
  <dbl> <int>
1     1     2
2     2     2
3     3     1

But i want to add a for loop to make this for each STYL... variable like this (i want to add in an excel workbook each data frame one under an other with openxlsx package):

list <- c("STYL1","STYL2","STYL3")
for (tempo_variable in list) {
  dt <- tested_data %>% 
    group_by(tempo_variable) %>% 
    count() %>% 
    ungroup()
}

it's important to me to make a loop because i don't know how many STYL... variables i'll have and i have to do this task for every STYL... variable. Someone have an idea how to do this ? Maybe i don't have to use a for loop ? Plz help me!

2

There are 2 best solutions below

2
On BEST ANSWER

Perhaps try something like this?

lapply(c("STYL1", "STYL2", "STYL3"), function(x, df) df %>% group_by(across(!!x)) %>% count() %>% ungroup(), tested_data)
0
On

You can tidy the data with tidyr::pivot_longer and then group by both columns in the output.

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

Created on 2020-10-19 by the reprex package (v0.3.0)