I'm trying to get the mean() and sum() for certain columns across rows. This code will produce the dataset:
library(tidyverse)
test_data <- tibble(part_id = 1:5,
a_1 = c("a", "b", "c", "d", "a"),
a_2 = c("b", NA, "b", "a", "d"),
a_3 = c("b", "b", "d", "d", "a"))
test_data <- test_data %>%
mutate_at(vars(a_1, a_2), .funs = list(scored = ~case_when(
. == "a" | . == "b" ~ 1,
. == "c" ~ 0,
. == "d" ~ -100)))
If I try to use rowSums() or rowMeans(), I get the correct answer:
library(tidyverse)
test_data <- test_data %>%
mutate(a_total = rowSums(dplyr::select(., contains("scored")), na.rm = TRUE),
a_mean = rowMeans(dplyr::select(., contains("scored")), na.rm = TRUE))
But, if try using rowwise() followed by sum() or mean(), it doesn't work:
library(tidyverse)
test_data <- test_data %>%
rowwise() %>%
mutate(a_total = base::sum(dplyr::select(., contains("scored")), na.rm = TRUE),
a_mean = base::mean(dplyr::select(., contains("scored")), na.rm = TRUE)) %>%
ungroup()
For sum(), it gives the total sum, effectively ignoring rowwise(), and for mean(), all answers are NA and I get this warning for each row:
Warning messages:
1: In mean.default(dplyr::select(., contains("scored")), na.rm = TRUE) :
argument is not numeric or logical: returning NA
I also tried this modification by including the c() function, as you would if you were to list each column. That resulted in the following error:
library(tidyverse)
test_data <- test_data %>%
rowwise() %>%
mutate(a_total = base::sum(c(dplyr::select(., contains("scored"))), na.rm = TRUE),
a_mean = base::mean(c(dplyr::select(., contains("scored"))), na.rm = TRUE)) %>%
ungroup()
Error in base::sum(c(dplyr::select(., contains("scored"))), na.rm = TRUE) :
invalid 'type' (list) of argument
How could I make this work with rowwise()? Why is this behaving so differently than typical and than rowSums() or rowMeans()?
I appreciate any insight!