简体   繁体   中英

R: Calculate standard deviation in cols in a data.frame despite of NA-Values

Good Morning, I got a lot of data and i have to calculate with it. There are 25 columns (variables) and each column contains thousands of values. But also missing values. I calculated the mean with

colMeans(df, na.rm = TRUE)

How can i calculate the sd of each column and ignore the NA-values?

You can try,

apply(df, 2, sd, na.rm = TRUE)

As the output of apply is a matrix, and you will most likely have to transpose it, a more direct and safer option is to use lapply or sapply as noted by @docendodiscimus,

sapply(df, sd, na.rm = TRUE)

If we convert to matrix , colSds from matrixStats can be used

library(matrixStats)
colSds(as.matrix(df), na.rm=TRUE) 

Or we can use summarise_each from dplyr

library(dplyr)
df1 %>%
    summarise_each(funs(sd(., na.rm=TRUE)))

由于函数summarise_each summarise_each()已被弃用,这里是使用dplyr的最新示例:

df1 %>% summarise_all(funs(sd(., na.rm = FALSE)))

sd(variablenname,na.rm=TRUE)

This works for me. Replace "variablename" with the variable you use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM