Home > database >  Calculating proportions based on conditions
Calculating proportions based on conditions

Time:10-06

please see sample data below:

data <- data.frame(q1=c(3,4,5,2,1,2,4),
                   q2=c(3,4,4,5,4,3,2),
                   q3=c(2,3,2,3,1,2,3),
                   q4=c(3,4,4,4,4,5,5))

I would like to create a another column which shows the percent of 4/5 responses. The output I am hoping to get looks something like this. Any help is appreciated, thank you!

 q1 q2 q3 q4 percent
1  3  3  2  3    0.00
2  4  4  3  4    0.75
3  5  4  2  4    0.75
4  2  5  3  4    0.50
5  1  4  1  4    0.50
6  2  3  2  5    0.25
7  4  2  3  5    0.50

CodePudding user response:

library(dplyr)
data <- data.frame(q1=c(3,4,5,2,1,2,4),
                   q2=c(3,4,4,5,4,3,2),
                   q3=c(2,3,2,3,1,2,3),
                   q4=c(3,4,4,4,4,5,5))

percent_4_5 <- function(x) {
  (sum(x == 4)   sum(x == 5)) / length(x)
}
data %>% rowwise() %>% mutate(percent = percent_4_5(c_across(starts_with("q")))) %>% ungroup()

CodePudding user response:

One possible solution:

data$percent = apply(data, 1, \(x) mean(x %in% 4:5))

  q1 q2 q3 q4 percent
1  3  3  2  3    0.00
2  4  4  3  4    0.75
3  5  4  2  4    0.75
4  2  5  3  4    0.50
5  1  4  1  4    0.50
6  2  3  2  5    0.25
7  4  2  3  5    0.50
  • Related