Guest User

Untitled

a guest
Jul 23rd, 2018
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. df <- data.frame(Q1 = c(1, 2, 1, 4), Q2 = c(4, 2, 3, 1), Q3 = c(3, 3, 2, 3),
  2. Q4 = c(4, 4, 2, 4), Q5 = c(4, 2, 3, 1), Q6 = c(7, 2, 3, 1))
  3.  
  4. library(dplyr)
  5.  
  6. df$mean <- df %>%
  7. select(Q1, Q2, Q3) %>%
  8. mutate_all(funs(. - 1)) %>%
  9. apply(1, function(x) {
  10. round(mean(x[!is.na(x) & x != 3]), digits = 2)
  11. })
  12.  
  13. df <- df %>%
  14. select(Q1, Q2, Q3) %>%
  15. mutate_all(funs(. - 1)) %>%
  16. mutate(mean = apply(., 1, function(x)
  17. round(mean(x[!is.na(x) & x != 3]), digits = 2)))
  18.  
  19. subtract <- c("Q1", "Q2", "Q3")
  20. df2 <- df %>%
  21. mutate_at(subtract, funs(. - 1)) %>%
  22. mutate(mean = apply(select(., one_of(subtract)), 1, function(x)
  23. round(mean(x[!is.na(x) & x != 3]), digits = 2)))
  24.  
  25. df2
  26. # Q1 Q2 Q3 Q4 Q5 Q6 mean
  27. # 1 0 3 2 4 4 7 1.00
  28. # 2 1 1 2 4 2 2 1.33
  29. # 3 0 2 1 2 3 3 1.00
  30. # 4 3 0 2 4 1 1 1.00
  31.  
  32. library(tidyverse)
  33.  
  34. df %>%
  35. select(1:3) %>%
  36. mutate_all(funs(. - 1)) %>%
  37. rowwise() %>%
  38. do( (.) %>% as.data.frame %>%
  39. mutate(mean = mean(.[. != 3], na.rm = TRUE)))
  40.  
  41. # Q1 Q2 Q3 mean
  42. #* <dbl> <dbl> <dbl> <dbl>
  43. #1 0 3.00 2.00 1.00
  44. #2 1.00 1.00 2.00 1.33
  45. #3 0 2.00 1.00 1.00
  46. #4 3.00 0 2.00 1.00
  47.  
  48. (df[1:3] - 1) %>%
  49. rowwise() %>%
  50. do( (.) %>% as.data.frame %>%
  51. mutate(mean = mean(.[. != 3], na.rm = TRUE)))
  52.  
  53. apply_fun <- function(x) {
  54. mean(x[x != 3], na.rm = TRUE)
  55. }
  56.  
  57. (df[1:3] - 1) %>%
  58. rowwise() %>%
  59. mutate(mean = apply_fun(c(Q1, Q2, Q3)))
  60.  
  61. # Q1 Q2 Q3 mean
  62. # <dbl> <dbl> <dbl> <dbl>
  63. #1 0 3.00 2.00 1.00
  64. #2 1.00 1.00 2.00 1.33
  65. #3 0 2.00 1.00 1.00
  66. #4 3.00 0 2.00 1.00
Add Comment
Please, Sign In to add comment