Reputation: 1484
Am not sure whether I have fully understood the rowwise
function in dplyr. I seem to get the expected results. Below is the code and the expected results.
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(.))
Upvotes: 2
Views: 411
Reputation: 886938
We may use pmap
which would be more efficient compared to rowwise
. Just loop over the data (cur_data()
), capture the row values as a vector (c(...)
) and get the 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.33
Upvotes: 0
Reputation: 10996
You need to wrap your columns into c_across
:
mydf %>%
rowwise() %>%
mutate(allmeanrow = mean(c_across(a1:a3))) %>%
ungroup()
which gives:
# 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
Note, i would always ungroup after the rowwise operation because rowwise groups your data by row, so any following action would still be performed rowwise.
See also here: https://dplyr.tidyverse.org/articles/rowwise.html
Upvotes: 3