Let's illustrate the problem on the famous iris
dataset. I need to apply the selected function by rows but only on selected columns. Example goes as follows:
library(tidyverse)
iris %>%
mutate_at(.funs = scale, .vars = vars(-c(Species))) %>%
rowwise() %>%
mutate(my_mean=mean(c(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width)))
So, first I scale all variables, excluding Species
and then compute mean rowwise over all four numeric variables. However, in the real dataset I have 100+ numeric variables and I wonder how to convince R to automatically include all variables excluding selected one (e.g., Species
in the given example). I go through the solutions on SO (e.g., this), but all examples explicitly refer to column names. Any pointers are greatly welcome.
EDIT: after some munging here is my solution:
iris %>%
as_tibble() %>%
mutate_at(.funs = scale, .vars = vars(-c(Species))) %>%
transmute(Species, row_mean = rowMeans(select(., -Species)))