Skip to content
Prev 385140 / 398503 Next

Arrange data

Hello,

Please keep cc-ing the list R-help is threaded and questions and answers 
might be of help to others in the future.

As for the question, see if the following code does what you want.
First, create a logical index i of the months between 7 and 3 and use 
that index to subset the original data.frame. Then, a cumsum trick gives 
a vector M defining the data grouping. Group and compute the Value means 
with aggregate. Finally, since each group spans a year border, create a 
more meaningful Years column and put everything together.

df1 <- read.csv("mddat.csv")

i <- with(df1, (Month >= 7 & Month <= 12) | (Month >= 1 & Month <= 3))
df2 <- df1[i, ]
M <- cumsum(c(FALSE, diff(as.integer(row.names(df2))) > 1))

agg <- aggregate(Value ~ M, df2, mean)
Years <- sapply(split(df2$Year, M), function(x){paste(x[1], 
x[length(x)], sep = "-")})
final <- cbind.data.frame(Years, Value = agg[["Value"]])

head(final)
#      Years    Value
#0 1975-1975 87.00000
#1 1975-1976 89.44444
#2 1976-1977 85.77778
#3 1977-1978 81.55556
#4 1978-1979 71.55556
#5 1979-1980 75.77778


Hope this helps,

Rui Barradas



?s 20:44 de 04/08/20, Md. Moyazzem Hossain escreveu: