Reputation: 5819
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
Reputation: 382
This should do the trick.
iris %>% mutate(stDev = apply(.[(1:4)],1,sd))
Upvotes: 4
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