library(tidyverse)
df <- tibble(col1 = c(5, 2), col2 = c(6, 4), col3 = c(9, 9))
# # A tibble: 2 x 3
# col1 col2 col3
# <dbl> <dbl> <dbl>
# 1 5 6 9
# 2 2 4 9
df %>% mutate(col4 = apply(.[, c(1, 3)], 1, sum))
df %>% mutate(col4 = rowSums(.[c(1, 3)], na.rm = TRUE))
Lately R's apply()
function has been trouble for me. For the time being I'm going to minimize it's use and use alternatives. @akrun educated me that I could use rowSums()
instead of apply()
as shown above, as an example.
But is there a way to apply, say, standard deviation across columns, like I do below. Obviously my imaginary::rowSd
function is not going to work. It's made up.
df %>% mutate(col4 = apply(.[, c(1, 3)], 1, sd))
df %>% mutate(col4 = imaginary::rowSd(.[c(1, 3)], na.rm = TRUE))
What is an approach that would work, without using apply()
? I'm thinking purrr although I've little knowledge on this package and the map()
functions. Maybe there's an even easier/elegant solution.
[EDIT] I should've mentioned I can't use column names because the names often change in the database I pull my info from. I can only use column numbers, because relative column position doesn't change in the database I pull data from.