Conditional summation over all data frames in R

I am working on transferring the analysis that I am doing in Excel to R as my dataset falls within Excel.

In Excel, I have a worksheet ("state") that performs the sumifs function, adding up values ​​from another sheet ("member") that have the same combination of states / weeks in a "state".

I would like to do this in R, where "state" and "member" are data.frames. Thus, for all the rows in the "state" data.frame, I would like to summarize all the rows from the "member" data.frame that have the same state / week combination in the "state".

Dataset

state=data.frame(state=c('MD','MD','MD','NY','NY','NY'), week = 1:3) 
member=data.frame(memID = 1:5, state = c('MD','MD','NY','NY','MD'),
              week = 1:3,
              value = c(24,43,34,54,33,35,33,11,42,23,14,12,42,4,23))

Desired output

state = data.frame(state=c('MD','MD','MD','NY','NY','NY'), week = 1:3, 
              total = c(80,90,70,96,15,76))

Thank!


Edit:

- . , , , , , 20 40?

state = data.frame(state=c('MD','MD','MD','NY','NY','NY'), week = 1:3, 
              total = c(80,33,58,0,0,34)    )
              state
+2
1

Try

 aggregate(value~state+week, member, sum)

 library(data.table)#v1.9.5+
 setDT(member)[, list(total=sum(value)), list(state, week)]

Update

sum "" 20 40.

setDT(member)[, sum(value[between(value,20,40)]) ,list(state, week)]
+1

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


All Articles