-1

I posted this question earlier but the suggestions was not very helpful may be because of unclear question. so sorry for cross posting. My data looks like

Months  value
 1  0
 2  0
 3  0
 4  0
 5  0
 6  0
 7  0
 8  0
 9  0
 10 0
 11 0
 12 0
 1  0
 2  0
 3  0
 4  20.32
 5  45.212
 6  27.178
 7  0
 8  0
 9  0
 10 0
 11 0
 12 0

No i want to add all 12 monthsin one place and get the new value so that my anwser could be 0 for first twelve months and 92.71 for second twelve months. I have a data of 150 years so any code please? Rosy

3
  • possible duplicate of Isum from cell 1 -12 in a column and repeat the same process
    – Metrics
    Mar 1, 2015 at 8:23
  • @Metrics the other way around. This version of the question is actually good. The previous one was just horrible and should be closed as a dupe of this. Not to mention that there are no answers in the other question. Mar 1, 2015 at 9:30
  • @rosyrana next time you can simply edit your previous question in stead of creating a new one, that is perfectly acceptable. Mar 1, 2015 at 10:54

2 Answers 2

3

We could use one of the aggregating functions after creating a grouping variable. Assuming that the 'Months' column is ordered, create the grouping variable (cumsum(df1$Months==1)) and get the sum

 tapply(df1$value, cumsum(df1$Months==1), FUN=sum, na.rm=TRUE)
 #   1     2 
 #0.00 92.71 

Or using data.table

 library(data.table)
 setDT(df1)[, list(SumValue=sum(value, na.rm=TRUE)),
              by=list(Group=cumsum(Months==1))]
 #   Group SumValue
 #1:     1     0.00
 #2:     2    92.71

We could also create the grouping variable using gl

 as.numeric(gl(nrow(df1), 12, nrow(df1)))
 #[1] 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2
2

Assuming your data are actually nicely ordered and complete, like you describe in the sample data, you can just convert the "value" column to a matrix and use rowSums on it:

matrix(mydf$value, ncol = 12, byrow = TRUE)
#      [,1] [,2] [,3]  [,4]   [,5]   [,6] [,7] [,8] [,9] [,10] [,11] [,12]
# [1,]    0    0    0  0.00  0.000  0.000    0    0    0     0     0     0
# [2,]    0    0    0 20.32 45.212 27.178    0    0    0     0     0     0
rowSums(matrix(mydf$value, ncol = 12, byrow = TRUE))
# [1]  0.00 92.71

Otherwise, more information would be required to make sure that the grouping of years is possible (as is done with @akrun's answer).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.