I am trying to calculate the mean and standard deviation from certain columns in a data frame, and return those values to new columns in the data frame. I can get this to wo
You can also write your own vectorised RowSD
function as in
RowSD <- function(x) {
sqrt(rowSums((x - rowMeans(x))^2)/(dim(x)[2] - 1))
}
and then
mtcars %>%
mutate(mean = (hp + drat + wt)/3, stdev = RowSD(cbind(hp, drat, wt)))
## mpg cyl disp hp drat wt qsec vs am gear carb mean stdev
## 1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 38.84000 61.62969
## 2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 38.92500 61.55489
## 3 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 33.05667 51.91809
## 4 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 38.76500 61.69136
## 5 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 60.53000 99.13403
## 6 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 37.07333 58.82726
## ...