counting same response in a row in R

Viewed 45

I have a data frame as below

multi_df <- data.frame( food=c("A","B","C"),
                        education=c("A","B","D"), 
                        health=c("F","C","A")
                       )

I want to check if more than 50% of columns have same response then I will flag it expected output is as below:

output <- multi_df %>%
  mutate ( flag= c("more than 50% response is same",
                   "more than 50% response is same",
                   "not same response")
          )

as seen in above food and education has same value i.e A which is more than 50% of all columns (3)

1 Answers

Write a function to calculate ratio of the highest frequency value in the row and return the text accordingly.

check_response <- function(x) {
  n <- sort(table(x), decreasing = TRUE)[1]
  if(n/length(x) > 0.5) "more than 50% response is same" else "not same response"
}

You can apply this function in base R using apply :

multi_df$flag <- apply(multi_df, 1, check_response)

Or with dplyr :

library(dplyr)

multi_df %>%
  rowwise() %>%
  mutate(flag = check_response(c_across()))

#  food  education health flag                          
#  <chr> <chr>     <chr>  <chr>                         
#1 A     A         F      more than 50% response is same
#2 B     B         C      more than 50% response is same
#3 C     D         A      not same response             
Related