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

New column with the count of columns that meet certain criteria

I searched a lot and I could not find a good solution for this simple problem. I tried rowSums, but with no success.

I have a df like the first image. I want to create a new column (V4), preferably using tidyverse, with the count of rows that meet a certain condition. In this example, the condition would be . == 5.

enter image description here

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

How many times number 5 appears in the other columns:

enter image description here

Example df

df <- data.frame(V1 = c(1,2,5,5,3),
                 V2 = c(1,5,5,5,5),
                 V3 = c(1,3,4,5,1))

>Solution :

We could use rowSums on a logical matrix

df$V4 <- rowSums(df == 5)

If we want a dplyr solution

library(dplyr)
df <- df %>%
   mutate(V4 = rowSums(cur_data() == 5))

Or may also use reduce

library(purrr)
df %>% 
   mutate(V4 = across(everything(), `==`, 5) %>%
           reduce(`+`))
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