简体   繁体   中英

Computation of the average of n observations in a data set using R

Please, how do I compute the average, that is, mean of the last 5 observations by class in a data: the first column is the class ie, Plot and the second column is the measured variable ie, 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

We select the last 5 observation for each 'Plot and get the mean

library(dplyr)
df1 %>%
    group_by(Plot) %>%
    summarise(MeanWt = mean(tail(Weight, 5)))

Or with data.table

library(data.table)
setDT(df1)[, .(MeanWt = mean(tail(Weight, 5))), by = Plot]

Or using base R

aggregate(cbind(MeanWt = Weight) ~ Plot, FUN = function(x) mean(tail(x, 5)))

I made this without a library: It's a step-by-step solution, of course you can make the code shorter using a for or apply. Hope you find it useful.

#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

To compute for the class 2 and 3 it's the same process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM