Question: I am trying to compute average scores for responses to different events. My data is in long format with one row for each event, sample dataset `data` here:

```
Subject  Event   R1  R2 R3 R4   Average
1        A       1   2  2  N/A   2.5
1        B       1   1  1  1     1

```

So to get the average for event A, it would be (R1 + R2 + R3)/3 ignoring the N/A, whereas event B has 4 responses. I computed the average for Event A in `dplyr` as: 

```
data$average <- data%>%filter(Event == "A") %>% with(data, (R1 + R2 + R3)/4) 

```

I ran into problems when I tried to do the same for the next event...Thank you for the help!

Answer: 
The following doesn't include the NA value as part of the mean calculation (*na.rm=TRUE*). Also, I think grouping by Event is important. When run without group\_by, the calculations combine all events and the resulting value is 1.285714 (=9/7 obs).

```
data <- data.frame(
  Subject=c(1,1),
  Event=c('A', 'B'),
  R1=c(1,1),
  R2=c(2,1),
  R3=c(2,1),
  R4=c(NA,1)
)

df <- data %>%
  group_by(Event) %>%
  mutate(Average = mean(c(R1,R2,R3,R4), na.rm=TRUE))

```

Output:

```
Subject Event    R1    R2    R3    R4 Average
    <dbl> <fct> <dbl> <dbl> <dbl> <dbl>   <dbl>
1       1 A         1     2     2    NA    1.67
2       1 B         1     1     1     1    1   

```
You can use `rowMeans` to calculate means for each row of a dataframe. Specify in the input which columns you want to include. To ignore the `NA` set `na.rm=TRUE`.

```
data$Average <- rowMeans(data[,c("R1", "R2", "R3", "R4")], na.rm=TRUE)

```

If you had lots of columns to average and didn't want to type them all out, you could use `grep` to match the names of `data` to any pattern. Say for example you want to average all the rows containing an "R" in their name:

```
data$Average <- rowMeans(data[,grep("R",names(data))], na.rm=TRUE)

```