如果可能的话,尝试使这些代码更优雅,更短 - R

时间:2016-05-10 21:12:46

标签: r mean

一个小背景:这是用于计算在研究过程中12天内进行的BOE 1鼠标平均距离的代码,每天重复4次实验。每个数据集中测试了19只小鼠。

问题:我想计算每只鼠标行进的平均距离并将其放入表中。我有什么作品,但我很好奇是否有办法让下面的代码更短,重复性更低。

尝试了选项:

mean(BOE.1Data$Distance.cm[BOE.1Data$Day == c(1,2, ect)]
mean(BOE.1Data$Distance.cm[BOE.1Data$Day == c(1|2| ect)]
mean(BOE.1Data$Distance.cm[BOE.1Data$Day == c(1&2& ect)]

这些都不适合我。

代码:

Distance.1 = c(mean(BOE.1Data$Distance.cm[BOE.1Data$Day == 1]),
               mean(BOE.1Data$Distance.cm[BOE.1Data$Day == 2]), 
               mean(BOE.1Data$Distance.cm[BOE.1Data$Day == 3]),
               mean(BOE.1Data$Distance.cm[BOE.1Data$Day == 4]),
               mean(BOE.1Data$Distance.cm[BOE.1Data$Day == 5]),
               mean(BOE.1Data$Distance.cm[BOE.1Data$Day == 6]),
               mean(BOE.1Data$Distance.cm[BOE.1Data$Day == 7]), 
               mean(BOE.1Data$Distance.cm[BOE.1Data$Day == 8]), 
               mean(BOE.1Data$Distance.cm[BOE.1Data$Day == 9]), 
               mean(BOE.1Data$Distance.cm[BOE.1Data$Day == 10]), 
               mean(BOE.1Data$Distance.cm[BOE.1Data$Day == 11]), 
               mean(BOE.1Data$Distance.cm[BOE.1Data$Day == 12]))

4 个答案:

答案 0 :(得分:3)

您可以使用$GIT_DIR/config

执行此操作
by()

答案 1 :(得分:2)

data.table的一种方法。将'data.frame'转换为'data.table'(setDT(BOE.1Data)),按'Day'分组,我们得到'Distance.cm'的mean

library(data.table)
setDT(BOE.1Data)[, .(MeanDist = mean(Distance.cm)) , by = Day]

答案 2 :(得分:0)

n <- numeric(length(12))
for (i in 1:12) {
    n[i] <- mean(BOE.1Data$Distance.cm[BOE.1Data$Day == i])
}

答案 3 :(得分:0)

使用dplyrmagrittr的另一种方法,使用arrange()确保它们按顺序排列。

Distance.1 <- BOE.1Data %>% group_by(Day) %>%
      mutate(mean_dist=mean(Distance.cm)) %>%
      arrange(Day) %$% mean_dist