计算R中列的平均值

时间:2017-07-19 18:27:08

标签: r mean

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)

有人可以告诉我怎么做我计算每个时间点的平均DV((DV1 + DV2 + DV3)/ 3)。平均值将表示来自所有ID&amp; amp;的时间点的平均DV。 DV(DV,DV2,DV3)也可获得95和5百分位数。

3 个答案:

答案 0 :(得分:1)

使用data.table包的示例:

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

但请确保在使用之前完全理解quantile,但我认为这是您正在寻找的功能。

答案 1 :(得分:1)

我有同样的问题,并使用dplyr包和管道来解决它。基本上,我首先选择我想要应用均值的列然后转置它们并将它们重新转换为数据帧并与原始数据帧合并...

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)

干杯

答案 2 :(得分:0)

使用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))

结果

# 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