Across

R
Author

Kevin

Published

2021-06-13

I made that more difficult than it had to be.

I was working on analyzing twenty plus survey questions and wanted to use the forcats function collapse on all of them. I was desperately trying to combine dplyr::across with the forcats function collapse.

Thankfully, I found this Stackoverflow Post

library(dplyr)
library(forcats)
df %>% 
    mutate(across(-pid, ~ fct_collapse(.,
     yes = c('y', 'Y'), no = c('no', 'NO', 'n'))))
     

My mistake was that I was trying to close the across function paren too soon and hence errors. Here is an example of one way I was doing it wrong.

library(dplyr)
library(forcats)
df %>% 
    mutate(across(-pid), ~ fct_collapse(.,
     yes = c('y', 'Y'), no = c('no', 'NO', 'n'))))
     

Conclusion

I am hoping that digging into the reason for this trouble helps me remember for next time.


About

Kevin is a nonprofit data professional operating out of Lakeland, Florida.
My expertise is helping nonprofits collect, manage and analyze their program data.