0

I have looked through other posts and cannot seem to find one that is exactly fitting to what I am trying to do.. It seems like a simple task but for some reason, I am completely stuck.

I have a dataset with multiple time points and a value for 1a and a value for 1b. A sample dataset looks as follows:

 Time   1a    1b
 -200  -0.02  -0.006
 -1.34 -0.003 -0.04
 0.536 0.057  0.0235

and so on (for 134 rows).

I am trying to aggregate column 1a and 1b to get one mean value for each time point. Could someone advise a solution for how to achieve this? I have tried

combined <- df %>% mutate(1 = mean(df$1a, df$1b)) %>% group_by(Time)

combined <- mutate(df , 1= mean(1a, 1b)) 

combined <- aggregate(df[,2:3], list(df$Time), mean)

None seem to give me this aggregated mean column of 1a and 1b. Any advice?

anelson
  • 55
  • 7

1 Answers1

1

You can use apply:

Data:

df <- data.frame(
  Time = c(-200, -1.34, 0.536),
  "1a" = c(-0.02, -0.003, 0.057),
  "1b" = c(-0.006, -0.04, 0.0235)
)

Solution:

df$mean <- apply(df[-1], 1, mean)

Result:

df
      Time    X1a     X1b     mean
1 -200.000 -0.020 -0.0060 -0.01300
2   -1.340 -0.003 -0.0400 -0.02150
3    0.536  0.057  0.0235  0.04025

Alternatively, as suggested by @jay.sf, use rowMeans, which is faster in terms of execution:

rowMeans(df[2:3])
[1] -0.01300 -0.02150  0.04025
Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34