I'm confused filling a "matrix" using tidyverse

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

instead of this part, try

out2 <- yyz %>% 
  summarise(across(num_range("type",1:4),
                   ~sum(.*dist))) %>% as.matrix()
2 Likes

It looks great.
By the way, can I apply your solution using group_by referering some variable?
Suppose I have zone as a new variable.

out2 <- yyz %>% group_by(zone) %>% 
  summarise(across(num_range("type",1:4),
                   ~sum(.*dist))) %>% as.matrix()

will the code above work?

I would expect that to work indeed.

I tested It. It worked so well.
Thanks, nirgrahamuk
This will make me avoid writing loops.
I hate loops in R.
Thanks again.

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.