I am wondering whether there is an R function or package for calculating Spearman correlation coefficient for each row in df and writing it as a vector?
Reproducible example first:
deviation <- c(5.712840e-03, 5.712840e-02, 5.712840e-01, 5.712940e-01,5.712840e-06)
number <- c(45, 60, 16, 70, 19)
df <- data.frame(deviation, number)
My df have 5 rows and 2 columns. I wanted to calculate Spearman correlation for each row, so that later I can add one more column with 5 rho's to my df. I understood there was a function cor.test that calculates the correlation coefficients. However, it doesn't help me to solve my task because I will get only one coefficient after it like
test <- cor.test(deviation, number, method="spearman")
test
It will give only one rho.
Could anyone, please, recommend me some package or function in R that can help to solve this task.
In addition to the comment of Ben Bolker I guess you are looking for something like this:
cor.test(df$deviation, df$number, method = "spearman")
gives
Spearman's rank correlation rho
data: df$deviation and df$number
S = 12, p-value = 0.5167
alternative hypothesis: true rho is not equal to 0
sample estimates:
rho
0.4
In order to put the estimates in a data frame you can use tidy()
from broom
package:
library(broom)
cor.test(df$deviation, df$number, method = "spearman") %>% tidy()
gives:
# A tibble: 1 x 5
estimate statistic p.value method alternative
<dbl> <dbl> <dbl> <chr> <chr>
1 0.4 12 0.517 Spearman's rank correlation rho two.sided
You then can make a function and use it:
cor_fun <- function(df) cor.test(df$deviation, df$number, method = "spearman") %>% tidy()
cor_fun(df)
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.