ash7on
ash7on

Reputation: 39

Is there a a way to make this function calculate sd as well as mean?

setNames(apply(cats, 1, , na.rm = TRUE), df[[1]])) 

I would like mean and sd to be outputted by one function.

Upvotes: 2

Views: 77

Answers (2)

linog
linog

Reputation: 6226

I don't know what is supposed to do cats in your example. So I will follow the title of your post.

With data.table, you can do complex calculations with lapply + .SD verbs in just one line :

library(data.table)
df = data.table(iris)
df[,lapply(.SD, function(x) return(c(mean(x, na.rm = TRUE), sd(x, na.rm = TRUE)))), .SDcols = colnames(df)[1]]
#  Sepal.Length
# 1:    5.8433333
# 2:    0.8280661

You can do that for more than one column if wanted

Upvotes: 1

akrun
akrun

Reputation: 887741

Here is an option with dplyr

library(dplyr)
iris %>%
  summarise_at(vars(Sepal.Length), list(mean = ~mean(., na.rm = TRUE), 
         sd = ~sd(., na.rm = TRUE)))
#      mean        sd
#1 5.843333 0.8280661   

Upvotes: 0

Related Questions