DiscoR
DiscoR

Reputation: 247

How to create a new average variable for which I have three values in separate rows?

My data looks like this

     subject treatment time outcome1 outcome2 
1       1         a    1       80       15
2       1         a    2       75       14
3       1         a    3       74       12
4       2         b    1       90       16
5       2         b    2       81       15
6       2         b    3       76       15

I would like to create a new variable that is an average of outcome1 values at time 1, 2, 3. I would like to do this for all subjects (40). I would then like to do this for outcome 2 till outcome 22.

I tried this

data <- data %>% 
group_by(subject) %>% 
summarise(mkcal = mean(kcal))

but it is giving wrong means and deleting all data except for means. When I try mutate instead of summarize it just creates a new column which is a copy of the kcal column. What am I doing wrong?

Thanks for reading.

Upvotes: 1

Views: 131

Answers (1)

tmfmnk
tmfmnk

Reputation: 39858

Using dplyr:

df %>%
  group_by(subject) %>%
  mutate_at(vars(contains("outcome")), funs(mean = mean(., na.rm = TRUE)))

# A tibble: 6 x 7
# Groups:   subject [2]
  subject treatment  time outcome1 outcome2 outcome1_mean outcome2_mean
    <int> <fct>     <int>    <int>    <int>         <dbl>         <dbl>
1       1 a             1       80       15          76.3          13.7
2       1 a             2       75       14          76.3          13.7
3       1 a             3       74       12          76.3          13.7
4       2 b             1       90       16          82.3          15.3
5       2 b             2       81       15          82.3          15.3
6       2 b             3       76       15          82.3          15.3

Data:

df <- read.table(text = "subject treatment time outcome1 outcome2 
1       1         a    1       80       15
           2       1         a    2       75       14
           3       1         a    3       74       12
           4       2         b    1       90       16
           5       2         b    2       81       15
           6       2         b    3       76       15", header = TRUE)

Upvotes: 2

Related Questions