I am trying to do a conditional summation based on a table that looks like this:
]1
I am trying to do a summation of the column "value" and group by Location. Normally I would just do this:
data <- file %>%
group_by(location, date) %>%
summarize(value = sum (value))
However, only for the Location "Central" I would like to exclude the Program "B". So I tried this way, but it did not work:
data <- file %>%
group_by(location, date) %>%
summarize(value =
case_when(location == "Central" ~ filter(program != "B")),
TRUE ~ sum(value)
)
If someone oculd please help me with the code above, I would much appreciate that. Thank you :)
EDIT: Here is the reproducible data using dput:
structure(list(pid = c(123, 123, 123, 123, 123, 123, 123,
123, 123, 123), program = c("A", "A",
"A", "A", "A",
"A", "A", "A",
"A", "A"), location = c("Central",
"Central", "Central", "Central", "Central", "Central", "Central",
"Central", "Central", "Central"), locationid = c("123-Central",
"123-Central", "123-Central", "123-Central", "123-Central",
"123-Central", "123-Central", "123-Central", "123-Central",
"123-Central"), date = structure(c(1302480000, 1305072000, 1307750400,
1310342400, 1313020800, 1315699200, 1318291200, 1323561600, 1326240000,
1328918400), tzone = "UTC", class = c("POSIXct", "POSIXt")),
value = c(37207.43, -56936.95, -52871, 6980.05, 10703.16,
4006.1, 6505.3, 9661.29, 6897.26, 7212.87)), row.names = c(NA,
-10L), class = c("tbl_df", "tbl", "data.frame"))