for 循环中的过滤或子集化

问题描述 投票:0回答:1

我正在尝试编写一个 for 循环来检查基于分组变量集的观测值的相对丰度是否总计为 100。在下面的简化示例中,我想检查是否所有与批次相关的相对丰度 (RelAb) 值A1加起来是100。

批量 阅读 相关抗体
A1 28431 72.94
A1 10549 27.06
B1 19315 85.96
B1 3155 14.04

如果我要逐一检查每个批次,我将不得不重复以下代码并每次将 Batch 更改为不同的对象。

test.batch <- data.batch %>%
  dplyr::filter(Batch == "A1")
sum(test.batch$RelAbByBatch)

我能够为手动检查的每个批次获取 100 的值,但我不想一次又一次重复同一行代码。

所以我尝试编写一个for循环:

Batches <- c("A1", "A2", "A3", "A4", "B1", "B2", "B3", "B4", "B5", "B6", "B7")
for(i in Batches) {
  filtered.batch <- data.batch %>%
     dplyr::filter(Batch %in% Batches)
  print(sum(filtered.batch$RelAb))

然而,循环有效,但每个变量的结果加起来并没有达到 100:

[1] 1100
[1] 1100
[1] 1100
[1] 1100
[1] 1100
[1] 1100
[1] 1100
[1] 1100
[1] 1100
[1] 1100
[1] 1100

顺便说一下,Batches 向量的长度是 11,但我不确定 100 的正确结果如何/为何乘以 11。

我还尝试了子集化而不是 dplyr::filter 但得到了与上面相同的结果。

for(i in Batches) {
  filtered.batch <- data.batch[data.batch$Batch %in% Batches]
  print(sum(filtered.batch$Batch))
}

我确信一个非常简单的解决方案可以解决这个问题(这甚至不紧急,因为重复一行代码 11 次并不是最大的问题),但我很好奇如何解决这个问题,这样我就可以写将来正确的代码。谢谢!

r for-loop dplyr subset
1个回答
0
投票
library(tidyverse)

df <- read_table("Batch Reads   RelAb
A1  28431   72.94
A1  10549   27.06
B1  19315   85.96
B1  3155    14.04")


df %>%  
  summarise(sum = sum(RelAb), 
            threshold = sum(RelAb) >= 100, 
            .by = Batch)

# A tibble: 2 x 3
  Batch   sum threshold
  <chr> <dbl> <lgl>         
1 A1      100 TRUE          
2 B1      100 TRUE
© www.soinside.com 2019 - 2024. All rights reserved.