r - handling NA values in apply functions returning more than one value -


i have dataframe df 2 columns col1, col2, includes na values in them. have calculate mean, sd them. have calculated them separately below code.

# random generation set.seed(12) df <- data.frame(col1 = sample(1:100, 10, replace=false),                   col2 = sample(1:100, 10, replace=false))  # introducing null values df$col1[c(3,5,9)] <- na df$col2[c(3,6)] <- na  # sapply return value function stat <- data.frame(mean=numeric(length = length(df)), row.names = colnames(df)) stat[,'mean'] <- as.data.frame(sapply(df, mean, na.rm=true)) stat[,'sd'] <- as.data.frame(sapply(df, sd, na.rm=true)) 

i have tried both operations @ single time using below code.

#sapply return more 1 value stat[,c('mean','sd')] <- as.data.frame(t(sapply(c(1:length(df)),function(x)     return(c(mean(df[,x]), sd(df[,x])))))) 

as failed remove na values in latest function, getting output na both mean, sd.

can please give idea on how remove na values each function mean, sd. also, please suggest other possible smart ways this.

here option:

funs <- list(sd=sd, mean=mean) sapply(funs, function(x) sapply(df, x, na.rm=t)) 

produces:

           sd       mean     col1.value 39.34826 39.42857 col2.value 28.33946 51.625   

if want cute functional library:

sapply(funs, curry(sapply, x=df), na.rm=t) 

does same thing.


Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -