Calculate conditional funds based on only one column in R

I have a dataframe like this:

block plot date data 1 1 aug 11.95171507 1 1 aug 18.41451063 1 2 aug 9.506155236 1 2 aug 13.26259947 1 3 aug 17.53616835 1 3 sep 15.40950767 2 1 sep 23.03616678 2 1 sep 17.07067258 2 2 sep 11.58278798 2 2 sep 13.15443304 

I would like to calculate the data facilities according to the schedule based on the block and date. In the end, I would like to have 5 means. Thank you for your help.

+4
source share
3 answers

Probably the path of least resistance is to use plyr :

 library(plyr) ddply(yourData, c("block", "date"), summarize, outVal = mean(data)) 

You can do similar things with data.table , aggregate , by and possibly a number of other functions. Take a few minutes to learn the R tag here on SO.

+5
source

Take a look at aggregate . I think you want to.

 d <- data.frame(block=c(1,1,1,1,1,1,2,2,2,2), plot=c(1,1,2,2,3,3,1,1,2,2), date=c(rep('aug',5),rep('sep',5)), data=c(11.95171507, 18.41451063, 9.506155236, 13.26259947, 17.53616835, 15.40950767, 23.03616678, 17.07067258, 11.58278798, 13.15443304)) aggregate(x = d$data, by = list(d$block, d$date), FUN = "mean") 
+3
source

Say your data is stored in a data frame called "DATA".

 > DATA block plot date data 1 1 1 aug 11.951715 2 1 1 aug 18.414511 3 1 2 aug 9.506155 4 1 2 aug 13.262599 5 1 3 aug 17.536168 6 1 3 sep 15.409508 7 2 1 sep 23.036167 8 2 1 sep 17.070673 9 2 2 sep 11.582788 10 2 2 sep 13.154433 

Then we can enter the following:

 > aggregate(DATA$data, list(Block = DATA$block, Date = DATA$date), mean) Block Date x 1 1 aug 14.13423 2 1 sep 15.40951 3 2 sep 16.21102 
+1
source

Source: https://habr.com/ru/post/1397647/


All Articles