Excel SUMIFS equivalent in R

前端 未结 4 546
后悔当初
后悔当初 2020-12-10 07:12

I\'m very very new to R and am looking at ways of recreating an Excel VBA macro and Excel worksheet functions such as SUMIFS. SUMIFS sums a column if the row has entries ma

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 07:48

    Assuming you have the above data in a data frame called df:

    sum(df$Sample[EndDate >= df$StartDate & StartDate <= df$EndDate])
    

    That is:

    • df$Sample[...] selects the Sample column, with conditions specified in [...]
    • EndDate >= df$StartDate and StartDate <= df$EndDate are from your example, converted to R conditions, with & in between to require both conditions to be true at the same time. Notice that there are no i indexes in the expression. That's how it works in R, the expression is evaluated for each row in the data frame, and the result of df$Sample[...] is a vector of values, only the values where the expression in [...] was true
    • sum is of course a built-in function to calculate the sum, naturally

提交回复
热议问题