-4
ID<-rep(1:6,each=3)
DV<-rep(1:6,each=3)
DV2<-rep(2:7,each=3)
DV3<-rep(3:8,each=3)
time<-rep(1:3,times=6)
df<-data.frame(ID,DV,DV2,DV3,time)

Can somebody please tell me how to do I calculate the mean DV ((DV1+DV2+DV3)/3) for each time point. The mean would represent the mean DV for that TIME point from all the ID's & DV's (DV,DV2,DV3) and also obtain 95 and 5 percentile ranges for the same.

Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194
  • You need `rowMeans` – G5W Jul 19 '17 at 18:29
  • Possible duplicate of [Analysis over time comparing 2 dataframes row by row](https://stackoverflow.com/questions/45149824/analysis-over-time-comparing-2-dataframes-row-by-row) – alaybourn Jul 19 '17 at 18:30
  • I think I misread your post. You want `DV` to be equal to `((DV1+DV2+DV3)/3)` across the columns, then compute the mean of `DV` for each value of `time` across the rows-- correct? – Damian Jul 19 '17 at 18:58
  • Also there is no `DV1` in the example – Damian Jul 19 '17 at 19:05

3 Answers3

1

An example using data.tablepackage:

require(data.table)
setDT(df)
df[, .(avg    = mean(DV + DV2 + DV3), 
       perc5  = quantile(DV + DV2 + DV3, 0.05), 
       perc95 = quantile(DV + DV2 + DV3, 0.95)), 
   by = time]


   time  avg perc5 perc95
1:    1 13.5  6.75  20.25
2:    2 13.5  6.75  20.25
3:    3 13.5  6.75  20.25

But make sure you understand quantile completely before using it but I think that is the function you are looking for.

M--
  • 25,431
  • 8
  • 61
  • 93
s_baldur
  • 29,441
  • 4
  • 36
  • 69
0

Using dplyr

library(dplyr)

df %>%
    rename(DV1 = DV) %>%
    mutate(DV = DV1 + DV2 + DV3) %>%
    group_by(time) %>%
    summarize(avg = mean(DV),
              p95 = quantile(DV, .95),
              p05 = quantile(DV, .05))

Result

# A tibble: 3 x 4
   time   avg   p95   p05
  <int> <dbl> <dbl> <dbl>
1     1  13.5 20.25  6.75
2     2  13.5 20.25  6.75
3     3  13.5 20.25  6.75
Damian
  • 1,385
  • 10
  • 10
0

I had the same problem and used the dplyr package and piping to solve it. Basically, I first select the columns I want to apply the mean on then transpose them and re-transform them into a data frame and merge with the original data frame...

bla <- data %>% select(seq(3,9,1)) %>% t %>% as.data.frame %>% 
sapply(mean) %>%  as.data.frame
colnames(bla) <- c("Mean")
data.audiogram <- cbind(data,bla)

Cheers