I've found an excellent solution to a problem I'm having where I want to create a new column that computes the mean of all the cells in the corresponding row here:
https://stackoverflow.com/a/33438918/12744116
The data is admittedly not tidy, but the solution, which I've copied below, gets the job done:
data %>%
rowwise() %>%
mutate(c=mean(c(a,b)))
# id a b c
# (dbl) (dbl) (dbl) (dbl)
# 1 101 1 2 1.5
# 2 102 2 2 2.0
# 3 103 3 2 2.5
However, unlike this simpler example, I have far too many columns to name. I'm wondering if there's any way of quickly referring to the columns using slicing notation (i.e., instead of c(a, b), something like 2:3) or some other way of referring to the columns via their index.
I've found something similar on another Stack Overflow thread here, but the solution has its own problems since we're listing all the column indices instead of the column names. I have way too many columns for me to list them all for each calculation.
Any solutions?
EDIT: I figured one out myself, but I feel like it's too inelegant and I believe I'm maybe extracting the entire column for every row, which is obviously going to be a slower solution than expected:
data %>%
mutate(id = row_number()) %>%
rowwise() %>%
mutate(avg = mean(c(.[id, 2:4], recursive=TRUE)))
Any solutions that are faster?