Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Count the number of observations across multiple columns and create new categories

I have data like these:

ID      color_1    color_2   color_3    color_4
1       blue        NA        NA         NA
5       green       blue      yellow     NA
9       None        NA        NA         NA 
2       blue        pink      NA         NA 
11      green       NA        NA         NA 

I want to add a new column that counts the number of colors (None, 1, or 2 or more):

ID      color_1    color_2   color_3    color_4    colors
1       blue        NA        NA         NA          1
5       green       blue      yellow     NA          2 or more
9       None        NA        NA         NA          None 
2       blue        pink      NA         NA          2 or more 
11      green       NA        NA         NA          1

I am thinking I can do something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

library(tidyverse)
data2 <- data %>%
 mutate(colors = case_when(
         color_1 == "None" ~ "None",
         

But I can’t figure out how to do the counting part. Any help is appreciated!

>Solution :

You can count using c_across and rowwise:

library(tidyverse)
df %>% 
  na_if("None") %>% 
  rowwise() %>% 
  mutate(count = sum(!is.na(c_across(color_1:color_4))),
         colors = case_when(count >= 2 ~ "2 or more",
                            count == 0 ~ "None",
                            T ~ as.character(count))) %>% 
  select(-count)

Output

     ID color_1 color_2 color_3 color_4 colors   
  <int> <chr>   <chr>   <chr>   <lgl>   <chr>    
1     1 blue    NA      NA      NA      1        
2     5 green   blue    yellow  NA      2 or more
3     9 NA      NA      NA      NA      None     
4     2 blue    pink    NA      NA      2 or more
5    11 green   NA      NA      NA      1        
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading