stackinator
stackinator

Reputation: 5819

R Standard Deviation Across Rows

The following code will sum columns 1 through 4 across each row in the iris data frame.

library(dplyr)
iris %>% mutate(sumVar = rowSums(.[1:4]))

How do I compute the standard deviation across these same four columns, for each row in the iris data frame? I want to avoid using column names and stick with the column numbers. My column names often change each time data is queried. This does not work:

library(dplyr)
iris %>% mutate(stDev = sd(.[1:4]))

Upvotes: 1

Views: 7661

Answers (3)

Markm0705
Markm0705

Reputation: 1440

This base R should do the trick?

apply(iris[ ,1:4],1,sd)

Upvotes: 1

Gangesh Dubey
Gangesh Dubey

Reputation: 382

This should do the trick.

iris %>% mutate(stDev = apply(.[(1:4)],1,sd))

Upvotes: 4

akrun
akrun

Reputation: 887731

We could convert it to matrix and then do the rowSds from matrixStats

library(matrixStats)
library(dplyr)
iris %>%
     mutate(stDev = rowSds(as.matrix(.[1:4])))

Upvotes: 2

Related Questions