【发布时间】:2022-11-15 01:02:13
【问题描述】:
我有一个数据,每次都有几个行 id 和 -infinite 值,我想使用 R 包 dplyr 和 tidyverse 来计算每次每个 ID 的 -infinite 平均数。
这是我的数据:
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))
在实际数据中,我有 100 多列,但为了简化,我只放了 x 和 y。
预期结果:
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
这个想法是根据特定的计算函数使用一些特定的列来生成一个向量。 搜索后我找到了 rowwise() 函数,但它没有帮助,这是我的尝试:
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
你能帮我生成这个向量 n 吗?
【问题讨论】:
-
我不确定您的数据是否可行。您的 12 行是 id 和时间的 12 个唯一组合。因此,对于每个子组,都有一个值,它要么是无限的(给 1),要么不是无限的(给 0)
-
抱歉,我现在知道您的目标是什么 -
x和y是两个观察结果,您对两者进行平均?看看下面的代码是否有帮助。