Hello,
I need to summarise some data using dplyr.
The issue is I created some binaries, and sometimes these binaries can be present in many columns. If you run the code I provided you will understand.
library(tidyverse)
yyz=datasets::cars
yyz=yyz %>% mutate(type1=if_else(speed %in% 2:25,1,0 ),
type2=if_else(speed %in% 2:10,1,0 ),
type3=if_else(speed %in% 8:10,1,0 ),
type4=if_else(speed %in% 11:25,1,0 ))
output=matrix(NA,1,4)
output[1,1]=sum(yyz$dist[yyz$type1==1])
output[1,2]=sum(yyz$dist[yyz$type2==1])
output[1,3]=sum(yyz$dist[yyz$type3==1])
output[1,4]=sum(yyz$dist[yyz$type4==1])
output
As you can see, type1 can be 1 and type2 also can be one. That's an example.
And I just want to declare the total sum of dist when type1 is 1, type2 is 1, and so on.
Then, bind all the results and made them look as the matrix output.
These is what I tried, but I failed
library(tidyverse)
yyz=datasets::cars
yyz=yyz %>% mutate(type1=if_else(speed %in% 2:25,1,0 ),
type2=if_else(speed %in% 2:10,1,0 ),
type3=if_else(speed %in% 8:10,1,0 ),
type4=if_else(speed %in% 11:25,1,0 ))
yyz %>%
group_by(across(num_range("type",1:4))) %>%
summarise(T_sum=sum(dist) )
As always, thanks for your time and interest.
Have a nice day, community