请问我该如何计算平均值,即数据中按类别分类的最后5个观察值的平均值:第一列是类别,即Plot,第二列是被测变量,即Weight。
Plot Weight
1 12.5
1 14.5
1 15.8
1 16.1
1 18.9
1 21.2
1 23.4
1 25.7
2 13.1
2 15.0
2 15.8
2 16.3
2 17.4
2 18.6
2 22.6
2 24.1
2 25.6
3 11.5
3 12.2
3 13.9
3 14.7
3 18.9
3 20.5
3 21.6
3 22.6
3 24.1
3 25.8
答案 0 :(得分:1)
我们为每个“图”选择最后5个观察值,并获得mean
library(dplyr)
df1 %>%
group_by(Plot) %>%
summarise(MeanWt = mean(tail(Weight, 5)))
或与data.table
library(data.table)
setDT(df1)[, .(MeanWt = mean(tail(Weight, 5))), by = Plot]
或使用base R
aggregate(cbind(MeanWt = Weight) ~ Plot, FUN = function(x) mean(tail(x, 5)))
答案 1 :(得分:0)
我没有图书馆就做到了: 这是一个循序渐进的解决方案,您当然可以使用for或Apply来缩短代码。 希望您觉得有用。
#Collecting your data
values <- scan()
1 12.5 1 14.5 1 15.8 1 16.1 1 18.9 1 21.2 1 23.4 1 25.7 2 13.1 2 15.0 2 15.8
2 16.3 2 17.4 2 18.6 2 22.6 2 24.1 2 25.6 3 11.5 3 12.2 3 13.9 3 14.7 3 18.9
3 20.5 3 21.6 3 22.6 3 24.1 3 25.8
data_w <- matrix(values, ncol=2, byrow = T)
#Naming your cols
colnames(data_w) <- c("Plot", "Weight")
dt_w <- as.data.frame(data_w)
#Mean of the 5 last observations by class:
#Computing number of Plots = 1
size1 <- length(which(dt_w$Plot == 1))
#Value to compute the last 5 values
index1 <- size1 - 5
#Way to compute the mean
mean1 <- mean(dt_w$Weight[index1:size1])
#mean of the last 5 observations of class 1
mean1
要计算第2类和第3类,这是相同的过程。