[英]Calculate pairwise correlation in R using dplyr::mutate
我有一個大數據框,每行都有足夠的數據來使用此數據框的特定列計算相關性,並添加一個包含計算出的相關性的新列。
這是我想要做的事情的摘要(這個使用 dplyr):
example_data %>%
mutate(pearsoncor = cor(x = X001_F5_000_A:X030_F5_480_C, y = X031_H5_000_A:X060_H5_480_C))
顯然它不是這樣工作的,因為我在 pearsoncor 列中只得到NA's
,有人有建議嗎? 有沒有簡單的方法來做到這一點?
最好的,
使用 tidyr,您可以分別收集所有想要比較的 x 和 y 變量。 您會得到一個包含相關系數及其 p 值的小標題,其中包含您提供的每個組合。
library(dplyr)
library(tidyr)
example_data %>%
gather(x_var, x_val, X001_F5_000_A:X030_F5_480_C) %>%
gather(y_var, y_val, X031_H5_000_A:X060_H5_480_C) %>%
group_by(x_var, y_var) %>%
summarise(cor_coef = cor.test(x_val, y_val)$estimate,
p_val = cor.test(x_val, y_val)$p.value)
編輯,幾年后更新:
library(tidyr)
library(purrr)
library(broom)
library(dplyr)
longley %>%
pivot_longer(GNP.deflator:Armed.Forces, names_to="x_var", values_to="x_val") %>%
pivot_longer(Population:Employed, names_to="y_var", values_to="y_val") %>%
nest(data=c(x_val, y_val)) %>%
mutate(cor_test = map(data, ~cor.test(.x$x_val, .x$y_val)),
tidied = map(cor_test, tidy)) %>%
unnest(tidied)
下面是使用的溶液reshape2
包melt()
該數據幀到長的形式,使得每個值具有其自己的行。 對於 6 個基因中的每一個,原始寬格式數據每行有 60 個值,而融合的長格式數據框有 360 行,每個值一個。 然后我們可以輕松地使用dplyr
summarize()
來計算沒有循環的相關性。
library(reshape2)
library(dplyr)
names1 <- names(example_data)[4:33]
names2 <- names(example_data)[34:63]
example_data_longform <- melt(example_data, id.vars = c('Gene','clusterFR','clusterHR'))
example_data_longform %>%
group_by(Gene, clusterFR, clusterHR) %>%
summarize(pearsoncor = cor(x = value[variable %in% names1],
y = value[variable %in% names2]))
您還可以使用do()
生成更詳細的結果,如 Eudald 的回答:
detailed_r <- example_data_longform %>%
group_by(Gene, clusterFR, clusterHR) %>%
do(cor = cor.test(x = .$value[.$variable %in% names1],
y = .$value[.$variable %in% names2]))
這會輸出一個 tibble,其中cor
列是一個列表,其中包含每個基因的cor.test()
結果。 我們可以使用lapply()
從列表中提取輸出。
lapply(detailed_r$cor, function(x) c(x$estimate, x$p.value))
幾天前我遇到了同樣的問題,我知道循環在 R 中不是最佳的,但這是我唯一能想到的:
df$r = rep(0,nrow(df))
df$cor_p = rep(0,nrow(df))
for (i in 1:nrow(df)){
ct = cor.test(as.numeric(df[i,cols_A]),as.numeric(df[i,cols_B]))
df$r[i] = ct$estimate
df$cor_p[i] = ct$p.value
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.