Home > Mobile >  Why I get NA when I tried to do a pearson correlation
Why I get NA when I tried to do a pearson correlation

Time:10-29

I am trying to do a pearson correlation with cor() function with this data sets

G1m: 1.0437500 1.0333333 0.9270833 0.7187500 0.3979167 
S1m: 0 0 0 0 0

like this:

cor(G1m,S1m)

And I get this:

NA
Warning message:
In cor(G1m, S1m) : the standard deviation is zero

Someone now which is the possible error and how can i fix it? Thank you!

CodePudding user response:

Your S1m vector values are all the same which means a standard deviation of 0. That's why you get the error:

NA Warning message: In cor(G1m, S1m) : the standard deviation is zero

Here is a reproducible example:

G1m <- c(1.0437500, 1.0333333, 0.9270833, 0.7187500, 0.3979167) 
S1m <- c(0, 0, 0, 0, 0)

# Correlation
cor(G1m, S1m)
#> Warning in cor(G1m, S1m): the standard deviation is zero
#> [1] NA

# Check standard deviations
sd(G1m)
#> [1] 0.2717357
sd(S1m)
#> [1] 0

When you change one value of S1m, you can see it works because of a non-zero sd:

# change one value in S1m to S1m2
S1m2 <- c(0, 0, 0, 0, 1)

# Cor again
cor(G1m, S1m2)
#> [1] -0.8768852

Created on 2022-10-28 with reprex v2.0.2

  •  Tags:  
  • r
  • Related