klumbard
klumbard

Reputation: 165

How to sum over NA rows by group in R

Let's say I have the following dataframe:

mydat <- structure(list(Group = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 2L
), .Label = c("A", "B"), class = "factor"), Day = c(1, 2, 3, 
1, 2, 3, 4), Var1 = c(2, 3, 5, 12, NA, NA, 51), Var2 = c(5, 6, 
2, 0, 40, 50, 3)), class = "data.frame", row.names = c(NA, -7L
))

mydat

  Group Day Var1 Var2
1     A   1    2    5
2     A   2    3    6
3     A   3    5    2
4     B   1   12    0
5     B   2   NA   40
6     B   3   NA   50
7     B   4   51    3

What I want to do (preferably with dplyr) is: by group, find the rows where Var1 is NA, and over those rows, sum up Var2 and include that sum in the next row in which Var1 is not NA. As such:

mydat_new <- structure(list(Group = structure(c(1L, 1L, 1L, 2L, 2L), .Label = c("A", 
"B"), class = "factor"), Day = c(1, 2, 3, 1, 4), Var1 = c(2, 
3, 5, 12, 51), Var2 = c(5, 6, 2, 0, 93)), class = "data.frame", row.names = c(NA, 
-5L))

mydat_new

  Group Day Var1 Var2
1     A   1    2    5
2     A   2    3    6
3     A   3    5    2
4     B   1   12    0
5     B   4   51   93

So in Group B, the rows with Days 2 and 3 are gone, and their Var2 contribution has been "absorbed" into the next Day whose Var1 is not NA, i.e. Day 4.

Upvotes: 2

Views: 68

Answers (1)

arg0naut91
arg0naut91

Reputation: 14764

One option would be:

library(dplyr)

mydat %>%
  group_by(Group, idx = rev(cumsum(rev(!is.na(Var1))))) %>%
  mutate(Var2 = sum(Var2)) %>%
  ungroup() %>%
  filter(!is.na(Var1)) %>%
  select(-idx)

Output:

# A tibble: 5 x 4
  Group   Day  Var1  Var2
  <fct> <dbl> <dbl> <dbl>
1 A         1     2     5
2 A         2     3     6
3 A         3     5     2
4 B         1    12     0
5 B         4    51    93

Upvotes: 2

Related Questions