我不确定我是否完全理解了dplyr中的rowwise函数。我似乎得到了预期的结果。下面是代码和预期结果。
library(dplyr)
set.seed(123)
mydf <- tibble(
a1 = floor(rnorm(10, 5, 2)),
a2 = floor(rnorm(10, 6, 3)),
a3 = floor(rnorm(10, 8, 3))
)
mydf %>%
rowwise() %>%
mutate(allmeanrow = mean(a1:a3))
# Expected
mydf %>%
mutate(allmeanrow = rowMeans(.))发布于 2021-10-07 07:55:51
您需要将列包装到c_across中
mydf %>%
rowwise() %>%
mutate(allmeanrow = mean(c_across(a1:a3))) %>%
ungroup()这就给出了:
# A tibble: 10 x 4
# Rowwise:
a1 a2 a3 allmeanrow
<dbl> <dbl> <dbl> <dbl>
1 3 9 4 5.33
2 4 7 7 6
3 8 7 4 6.33
4 5 6 5 5.33
5 5 4 6 5
6 8 11 2 7
7 5 7 10 7.33
8 2 0 8 3.33
9 3 8 4 5
10 4 4 11 6.33请注意,我总是在按行操作后取消分组,因为按行对数据进行分组,因此任何后续操作仍将按行执行。
发布于 2021-10-07 17:54:04
我们可以使用与rowwise相比效率更高的pmap。只需循环遍历数据(cur_data()),以向量形式捕获行值(c(...))并获得mean
library(purrr)
library(dplyr)
mydf %>%
mutate(allmeanrow = pmap_dbl(cur_data(), ~ mean(c(...))))
# A tibble: 10 × 4
a1 a2 a3 allmeanrow
<dbl> <dbl> <dbl> <dbl>
1 3 9 4 5.33
2 4 7 7 6
3 8 7 4 6.33
4 5 6 5 5.33
5 5 4 6 5
6 8 11 2 7
7 5 7 10 7.33
8 2 0 8 3.33
9 3 8 4 5
10 4 4 11 6.33https://stackoverflow.com/questions/69477343
复制相似问题