I have 3 groups for which I have collected data for 12 months for 4 variables for some group * month combination, any of the of variable might have an -Inf value.
temp <- data.frame(group_id = rep(1:3, each = 12),
Month = rep(1:12, times = 3),
var1 = c(-Inf, rnorm(35)),
var2 = rnorm(36),
var3 = rnorm(36),
var4 = c(rnorm(35), -Inf))
In the above sample data, group 1 and 3 should be dropped and only group 2 should remain.
I have a rather tedious way to achieve it. I look for each of my column whether infinite value is present for any given group and then remove them as shown below. The problem is if I have more than 4 variables, this will become quite lengthy.
library(dplyr)
group_to_keep <-
temp %>%
dplyr::group_by(group_id) %>%
dplyr::summarise(var1_inf = sum(is.infinite(var1)),
var2_inf = sum(is.infinite(var2)),
var3_inf = sum(is.infinite(var3)),
var4_inf = sum(is.infinite(var4))) %>%
rowwise %>%
dplyr::mutate(row_sum = sum(var1_inf:var4_inf)) %>%
dplyr::mutate(row_sum = ifelse(row_sum != 0, NA, row_sum)) %>%
tidyr::drop_na()
temp %>% dplyr::filter(group_id %in% group_to_keep$group_id)