使用 dplyr::mutate 计算 R 中的成对相关性

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,有人有什么建议吗?有没有简单的方法可以做到这一点?

最佳,

Example data frame

几天前我遇到了同样的问题,我知道循环在 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
}

这是一个使用 reshape2 包将数据框 melt() 转换为长格式的解决方案,以便每个值都有自己的行。原始 wide-form 数据的 6 个基因每行有 60 个值,而融化的 long-form 数据框有 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]))

您还可以生成更详细的结果,如 Eudald 的回答,使用 do():

detailed_r <- example_data_longform %>%
  group_by(Gene, clusterFR, clusterHR) %>%
  do(cor = cor.test(x = .$value[.$variable %in% names1],
                    y = .$value[.$variable %in% names2]))

这会输出一个小标题,其中 cor 列是每个基因的 cor.test() 结果列表。我们可以使用 lapply() 从列表中提取输出。

lapply(detailed_r$cor, function(x) c(x$estimate, x$p.value))

有了tidyr,你可以单独收集所有x-和y-variables,你想比较一下。您会得到一个小标题,其中包含您提供的每个组合的相关系数及其 p-values。

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)