student24
student24

Reputation: 252

How to calculate standard deviation per row?

I am trying to calculate a standard deviation per row

The example of the input (values_for_all):

1  0.35 0.35 4.33 0.09 4.17 0.16 9.90 15.25 0.16 2.38 2.55 8.14 0.16 NA 0.16
2  8.75 3.22 7.34 0.56 2.43 0.23 1.20 8.45 1.26 NA NA 1.24 0.16 2.34 0.36

Code:

values_for_all[values_for_all == ''] <- NA
values_for_all[] <- lapply(values_for_all, as.numeric)
values_mean <- rowMeans(values_for_all, na.rm=TRUE) 

#calculating standard deviation per row 
SD <- rowSds(values_for_all, na.rm=TRUE)
SD

The first part (values_mean) works perfectly. Unfortunately, the part with SD doesn't.

Upvotes: 1

Views: 610

Answers (3)

jay.sf
jay.sf

Reputation: 73572

You're using matrixStats which implies that the function should be applied to matrices. Hence wrap as.matrix around your data frame.

matrixStats::rowSds(as.matrix(dat), na.rm=TRUE)
# [1] 4.515403 3.050903

Upvotes: 1

M&#229;nsT
M&#229;nsT

Reputation: 974

apply lets you apply a function to all rows of your data:

apply(values_for_all, 1, sd, na.rm = TRUE)

To compute the standard deviation for each column instead, replace the 1 by 2.

Upvotes: 1

Chris Ruehlemann
Chris Ruehlemann

Reputation: 21432

You can use apply:

apply(df, 1, sd)

Upvotes: 0

Related Questions