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 work for mean:
library(dplyr)
mtcars = mutate(mtcars, mean=(hp+drat+wt)/3)
However, when I try to do the same for standard deviation, I have an issue, because I cannot hardcode the equation like I did for mean very easily. So, I try to use a function, as follows:
mtcars = mutate(mtcars, mean=(hp+drat+wt)/3, stdev = sd(hp,drat,wt))
Resulting in the error "Error in sd(hp, drat, wt) : unused argument (wt)". How can I correct my syntax? Thank you.
sd
function is some strange way. Doesn't it look inconsistent to you? – Confluxsd
is incorrect, which it is, in a commonly mistaken way. For instance, trysd(1,2,3)
, then read?sd
and see (1) that it describes the first argument as "x: a numeric vector", and (2) it specifically does not include "..." (ellipses, that would allow for an arbitrary number of arguments as you are providing). – Densmore+
to get mean may not work as expected if there are NA's, In themean
androwMeans
, there are options for removing NA, ie.na.rm=TRUE
. – Langue