Home > Mobile >  Is there a way to use rowwise to get means across rows the correct way?
Is there a way to use rowwise to get means across rows the correct way?

Time:10-07

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(.))

CodePudding user response:

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

  • Related