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.
How many times number 5 appears in the other columns:
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(`+`))

