Pearson的相关系数来自r中的两个表

时间:2018-05-09 22:29:17

标签: r dataframe statistics bioinformatics biomart

我有以下两个数据集:

df <- read.table(text =
                   "Human_Gene_Name hsapiens    mmusculus   ggallus celegans    dmelanogaster   cintestinalis   trubripes   xtropicalis mmulatta
A1CF    5.634789603 4.787491743 3.688879454 2.079441542 3.931825633 2.772588722 3.871201011 3.044522438 4.094344562
                 AAK1   3.583518938 2.708050201 2.079441542 2.197224577 2.079441542 0.693147181 2.772588722 2.079441542 3.218875825
                 AAMP   3.555348061 3.17805383  2.48490665  1.791759469 2.302585093 0.693147181 2.48490665  1.098612289 2.079441542", header  = T)

ctn_df <- read.table(text = "Species    CTN
                     hsapiens   158
                     mmusculus  85
                     ggallus    67
                     celegans   32
                     dmelanogaster  27
                     cintestinalis  19
                     trubripes  110
                     xtropicalis    82
                     mmulatta   71
                     ", header = T)

'df'中的值代表功能性疏散,我想根据物种CTN和功能多样性计算每个基因的皮尔森相关系数。

有没有办法可以根据'ctn_df'中的数据轻松地将CTN分配到表'df'中的特定物种。

很抱歉,如果这是一个简单的问题。

2 个答案:

答案 0 :(得分:2)

使用apply将行数值连续传递给cor作为第一个参数,然后将相关值命名为第一列:

setNames( apply(df[-1], 1, cor, ctn_df$CTN), df$Human_Gene_Name)
     A1CF      AAK1      AAMP 
0.7556590 0.7834861 0.6829534 

答案 1 :(得分:0)

这是一个Tidyverse解决方案:

library(tidyverse)

gather(df, Species, functional_diveresity, -Human_Gene_Name) %>%
  left_join(ctn_df) %>%
  group_by(Human_Gene_Name) %>%
  summarise(cor(functional_diveresity, CTN))

#  # A tibble: 3 x 2
#   Human_Gene_Name `cor(functional_diveresity, CTN)`
#   <fct>                                       <dbl>
# 1 A1CF                                        0.756
# 2 AAK1                                        0.783
# 3 AAMP                                        0.683

前两行产生tidy dataframe,使下游计算更容易:

gather(df, Species, functional_diveresity, -Human_Gene_Name) %>%
  left_join(ctn_df)

#    Human_Gene_Name       Species functional_diveresity CTN
# 1             A1CF      hsapiens             5.6347896 158
# 2             AAK1      hsapiens             3.5835189 158
# 3             AAMP      hsapiens             3.5553481 158
# 4             A1CF     mmusculus             4.7874917  85
# 5             AAK1     mmusculus             2.7080502  85
# 6             AAMP     mmusculus             3.1780538  85
# ....