I have a data with several line ids per time and with -infinite values, and I would like to use the R packages dplyr and tidyverse to calculate the average number of -infinite per ID per time.
This is my data:
dt <- data.frame(id = rep(1:3, each = 4),
time = rep(1:4, time=3),
x = c(1, 2, 1, -Inf, 2, -Inf,1, 1, 5, 1, 2, 1),
y = c(2, -Inf, -Inf, -Inf, -Inf, 5, -Inf, 2, 1, 2, 2, 2))
In the real data I have more than 100 columns but to simplify I put only x and y.
The expected result:
id time n
2 1 2 0.5
3 1 3 0.5
4 1 4 1.0
5 2 1 0.5
6 2 2 0.5
7 2 3 0.5
The idea is to use some specific columns to generate a vector according to a specific calculation function. After searching I found the rowwise() function, but it did not help, Here is my attempt:
dt %>%
group_by(id,time) %>%
summarise(n = across(x:y, ~mean(is.infinite(x) & x < 0, na.rm=TRUE)))
dt %>%
group_by(id,time) %>%
rowwise() %>%
summarise(n = across(everything(), ~mean(is.infinite(x) & x < 0, na.rm=TRUE)))
dt %>%
rowwise() %>%
summarise(n = across(everything(), ~mean(is.infinite(x) & x < 0, na.rm=TRUE)))
# same results:
`summarise()` has grouped output by 'id'. You can override using the `.groups` argument.
# A tibble: 12 x 3
# Groups: id [3]
id time n$x $y
<int> <int> <dbl> <dbl>
1 1 1 0 0
2 1 2 0 0
3 1 3 0 0
4 1 4 1 1
5 2 1 0 0
6 2 2 1 1
7 2 3 0 0
8 2 4 0 0
9 3 1 0 0
10 3 2 0 0
11 3 3 0 0
12 3 4 0 0
Could you help me to generate this vector n?