R/tidyverse: calculating standard deviation across rows
Try this (using), withrowSds
from the matrixStats
package,
library(dplyr)
library(matrixStats)
columns <- c('colB', 'colC', 'colD')
df %>%
mutate(Mean= rowMeans(.[columns]), stdev=rowSds(as.matrix(.[columns])))
Returns
colA colB colC colD Mean stdev
1 SampA 21 15 10 15.33333 5.507571
2 SampB 20 14 22 18.66667 4.163332
3 SampC 30 12 18 20.00000 9.165151
Your data
colA <- c("SampA", "SampB", "SampC")
colB <- c(21, 20, 30)
colC <- c(15, 14, 12)
colD <- c(10, 22, 18)
df <- data.frame(colA, colB, colC, colD)
df
Here is another way using pmap
to get the rowwise mean
and sd
library(purrr)
library(dplyr)
library(tidur_
f1 <- function(x) tibble(Mean = mean(x), SD = sd(x))
df %>%
# select the numeric columns
select_if(is.numeric) %>%
# apply the f1 rowwise to get the mean and sd in transmute
transmute(out = pmap(., ~ f1(c(...)))) %>%
# unnest the list column
unnest %>%
# bind with the original dataset
bind_cols(df, .)
# colA colB colC colD Mean SD
#1 SampA 21 15 10 15.33333 5.507571
#2 SampB 20 14 22 18.66667 4.163332
#3 SampC 30 12 18 20.00000 9.165151
Package magrittr
pipes %>%
are not a good way to process by rows.
Maybe the following is what you want.
df %>%
select(-colA) %>%
t() %>% as.data.frame() %>%
summarise_all(sd)
# V1 V2 V3
#1 5.507571 4.163332 9.165151