首页 > 解决方案 > R中的复杂循环或函数

问题描述

所以我最近开始写一般的代码,我被困在这里好几天了。

在一个简单的范围内,我有两个数据框,实际上我需要做的是

(moduletotals$Freq[3] - totals_df$Freq[1])

从每行的暗橙色模块簇 1 中的“2'-脱氧核糖核苷酸生物合成”的频率中减去暗橙色模块的总数,簇 1 totals_df

但我有太多数据需要构建一个循环、函数或类似的东西,函数可以从单个样本中找到相关模块和集群的总频率。沿着这些思路

> moduletotals$module == totals_df$module & 
    moduletotals$cluster == totals_df$cluster 

打印freq找到的行并将其从相关的 totals_df 行的频率中减去

我完全迷失在这里。

模块总数

模块 频率
深绿色 1 12
深灰色 1 408
暗橙 1 355
深红 1 11
深绿松石色 1 12
灰色的 1 22

总计_df

类描述 模块 频率
2'-脱氧核糖核苷酸生物合成 暗橙 1 1
2'-脱氧核糖核苷酸生物合成 深灰色 2 1
2'-脱氧核糖核苷酸生物合成 暗橙 2 3
适应和非典型条件 暗橙 1 1
适应和非典型条件 深灰色 2 1
有氧运动 深灰色 1 4
有氧运动 暗橙 1 3
有氧运动 灰色60 1 2
有氧运动 淡黄色 1 3
有氧运动 宝蓝色 1 1

标签: r

解决方案


您可以left_join在数据框之间执行:

library(tidyverse)

module <- data.frame(
  stringsAsFactors = FALSE,
  module = c(
    "darkgreen",
    "darkgrey",
    "darkorange",
    "darkred",
    "darkturquoise",
    "grey"
  ),
  cluster = c(1L, 1L, 1L, 1L, 1L, 1L),
  freq = c(12L, 408L, 355L, 11L, 12L, 22L)
)

totals <- data.frame(
  stringsAsFactors = FALSE,
  class_description = c(
    "Adaptions and atypical conditions",
    "Adaptions and atypical conditions",
    "Aerobic",
    "Aerobic",
    "Aerobic",
    "Aerobic",
    "Aerobic"
  ),
  module = c(
    "darkorange",
    "darkgrey",
    "darkgrey",
    "darkorange",
    "grey60",
    "lightyellow",
    "royalblue"
  ),
  cluster = c(1L, 2L, 1L, 1L, 1L, 1L, 1L),
  freq = c(1L, 1L, 4L, 3L, 2L, 3L, 1L)
)

totals %>%
  left_join(module,
            by = c("module", "cluster")) %>%
  replace_na(list(freq.y = 0))
#>                   class_description      module cluster freq.x freq.y
#> 1 Adaptions and atypical conditions  darkorange       1      1    355
#> 2 Adaptions and atypical conditions    darkgrey       2      1      0
#> 3                           Aerobic    darkgrey       1      4    408
#> 4                           Aerobic  darkorange       1      3    355
#> 5                           Aerobic      grey60       1      2      0
#> 6                           Aerobic lightyellow       1      3      0
#> 7                           Aerobic   royalblue       1      1      0


module %>%
  left_join(
    totals %>%
      group_by(module, cluster) %>%
      summarise(freq = sum(freq),
                .groups = "drop"),
    by = c("module", "cluster")
  ) %>%
  replace_na(list(freq.y = 0))
#>          module cluster freq.x freq.y
#> 1     darkgreen       1     12      0
#> 2      darkgrey       1    408      4
#> 3    darkorange       1    355      4
#> 4       darkred       1     11      0
#> 5 darkturquoise       1     12      0
#> 6          grey       1     22      0

推荐阅读