0

I would like to compute the row mean scores of columns A1 to E1.

library(dplyr)
df <- data.frame(A1 = c(1, 2, NA, 4),
                     B1 = c(2, 4, NA, 9),
                     C1 = c(6, 12, NA, 6),
                     D1 = c(22, 7, NA, 1),
                     E1 = c(11, 40, NA, 7),
                     F1 = c(22, 7, NA, 1),
                     G1 = c(2, 4, NA, 9),
                     H1 = c(11, 40, NA, 10)
               )
> df
  A1 B1 C1 D1 E1 F1 G1 H1
1  1  2  6 22 11 22  2 11
2  2  4 12  7 40  7  4 40
3 NA NA NA NA NA NA NA NA
4  4  9  6  1  7  1  9 10

This is my code so far:

df <- df %>%
  mutate(meanscores = rowMeans(subset(select = A1:E1)), na.rm = TRUE)

Thanks in advance!

Anoushiravan R
  • 21,622
  • 3
  • 18
  • 41
Marie
  • 267
  • 1
  • 8
  • 16
  • 1
    There's probably other more *dplyr*ier ways to do it, but you just need to reference the data with `.` when you do `subset` and it will work: `df %>% mutate(meanscores = rowMeans(subset(., select = A1:E1), na.rm = TRUE))` - and make sure `na.rm=TRUE` is passed as an argument to `rowMeans` and not to `mutate` – thelatemail Apr 28 '21 at 00:43
  • 1
    I think the current preferred method however is `df %>% mutate(rs = rowMeans(across(A1:E1), na.rm=TRUE))` – thelatemail Apr 28 '21 at 00:49
  • This is working, thank you! – Marie Apr 28 '21 at 00:53

1 Answers1

1

Here's a solution using base R.

mean_result <- rowMeans(df[,1:5], na.rm = TRUE)
eduardokapp
  • 1,612
  • 1
  • 6
  • 28