Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- df <- data.frame(Q1 = c(1, 2, 1, 4), Q2 = c(4, 2, 3, 1), Q3 = c(3, 3, 2, 3),
- Q4 = c(4, 4, 2, 4), Q5 = c(4, 2, 3, 1), Q6 = c(7, 2, 3, 1))
- library(dplyr)
- df$mean <- df %>%
- select(Q1, Q2, Q3) %>%
- mutate_all(funs(. - 1)) %>%
- apply(1, function(x) {
- round(mean(x[!is.na(x) & x != 3]), digits = 2)
- })
- df <- df %>%
- select(Q1, Q2, Q3) %>%
- mutate_all(funs(. - 1)) %>%
- mutate(mean = apply(., 1, function(x)
- round(mean(x[!is.na(x) & x != 3]), digits = 2)))
- subtract <- c("Q1", "Q2", "Q3")
- df2 <- df %>%
- mutate_at(subtract, funs(. - 1)) %>%
- mutate(mean = apply(select(., one_of(subtract)), 1, function(x)
- round(mean(x[!is.na(x) & x != 3]), digits = 2)))
- df2
- # Q1 Q2 Q3 Q4 Q5 Q6 mean
- # 1 0 3 2 4 4 7 1.00
- # 2 1 1 2 4 2 2 1.33
- # 3 0 2 1 2 3 3 1.00
- # 4 3 0 2 4 1 1 1.00
- library(tidyverse)
- df %>%
- select(1:3) %>%
- mutate_all(funs(. - 1)) %>%
- rowwise() %>%
- do( (.) %>% as.data.frame %>%
- mutate(mean = mean(.[. != 3], na.rm = TRUE)))
- # Q1 Q2 Q3 mean
- #* <dbl> <dbl> <dbl> <dbl>
- #1 0 3.00 2.00 1.00
- #2 1.00 1.00 2.00 1.33
- #3 0 2.00 1.00 1.00
- #4 3.00 0 2.00 1.00
- (df[1:3] - 1) %>%
- rowwise() %>%
- do( (.) %>% as.data.frame %>%
- mutate(mean = mean(.[. != 3], na.rm = TRUE)))
- apply_fun <- function(x) {
- mean(x[x != 3], na.rm = TRUE)
- }
- (df[1:3] - 1) %>%
- rowwise() %>%
- mutate(mean = apply_fun(c(Q1, Q2, Q3)))
- # Q1 Q2 Q3 mean
- # <dbl> <dbl> <dbl> <dbl>
- #1 0 3.00 2.00 1.00
- #2 1.00 1.00 2.00 1.33
- #3 0 2.00 1.00 1.00
- #4 3.00 0 2.00 1.00
Add Comment
Please, Sign In to add comment