tidyverse - Using summarise_at in order to sum a column

I want to avoid declaring a loop. I am creating some dummies, and then, using summarise_at I would like just to sum the column "fact" for each vars I created. I tried something like this:

data=data %>% mutate(s1=if_else(clasifier==1,1,0),s2=if_else(clasifier==21,1,0),
                       s3=if_else(clasifier %in% 3:4,1,0),s4=if_else(clasifier %in% 5:6,1,0),s5=if_else(clasifier==7,1,0))
data %>% group_by(zone) %>% summarise_at(vars(s1:s5),sum(fact,na.rm=TRUE))

But I receive a message
Error in is_fun_list(.funs) : objet 'fact_cal' introuvable

What am I doing wrong?
I mean, I plan to sum fact for s1,s2,...,s5 and grouping that operation by zone.
Is it possible? Is there an alternative?
Thanks for your time and interest.

What does your dataset look like? Can you provide an example?

1 Like

The data is here:

It is blocked for me (from work). Can you post a reproducible example?

datos=datos %>% mutate(s1=if_else(block==1,1,0),s2=if_else(block==2,1,0),
                       s3=if_else(block %in% 3:4,1,0),s4=if_else(block %in% 5:6,1,0))

datos %>% group_by(N) %>% summarise_at(vars(s1:s4),sum(yield),na.rm=T)

The idea is recreate the results from this code

datos %>% group_by(N,s1) %>% summarise(suma=sum(yield))
datos %>% group_by(N,s2) %>% summarise(suma=sum(yield))
datos %>% group_by(N,s3) %>% summarise(suma=sum(yield))
datos %>% group_by(N,s4) %>% summarise(suma=sum(yield))
datos %>% group_by(N,s5) %>% summarise(suma=sum(yield))

But I don't want to write four times the same code, and I don't want to declare a loop.
I hope my explanation is clear.
Thanks for your time, guys.

Try this.

datos %>% 
  pivot_longer(s1:s4) %>%
  group_by(N, name, value) %>% 
  summarize(suma = sum(yield), .groups = "drop")
1 Like

I should explain you don't want to summarize_at(vars(s1:s4)) because the column you want to summarize seems to be yield. It seems like instead you want to use s1:s4 as grouping variables, so it makes sense to pivot them so their values appear across rows and can be used in the group_by.

Thanks. It worked without error.
I will read the code in order to learn It well.
This way I will avoid writing loops.
Thanks again, arthur.t

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.