繁体   English   中英

R:如何在我的数据帧的所有列中删除 tidyverse 组中的单例?

[英]R : How can I remove singletons within tidyverse groups across all columns of my dataframe?

我正在研究一个大型 ASV 检测数据集,其中每个样本名称都有来自不同 PCR 运行的三个重复。 我的目标是从数据集中删除单身人士。 这意味着如果一个样本名称在所有三个复制中只有一个 ASV 检测,我希望将 1 变成零。

到目前为止,我已经能够使用 3 个 ASV 在小范围内完成此操作,但我的方法要求我写出每个 ASV 名称。 这对我不起作用,因为我的数据集有 9000 个 ASV。 我需要一个更好的方法来删除单身人士。

这是我到目前为止所做的:

#make dataframe
sample.name <- c("a","a","a","b","b","b","c","c","c")
data <- as.data.frame(sample.name)
data$sample.pcr <- c("1","2","3","1","2","3","1","2","3")
data$AVS1 <- c(3,1,0,1,0,0,0,0,1)
data$AVS2 <- c(0,1,0,2,3,0,1,0,0)
data$AVS3 <- c(0,0,1,0,0,0,0,5,0)

#mutate so that if the sum of a sample.name group is 1 for an ASV then make that sum 0
data %>%
  group_by(sample.name) %>%
  mutate(AVS1 = case_when(sum(AVS1)==1 ~ 0,
                          T ~ AVS1),
         AVS2 = case_when(sum(AVS2)==1 ~ 0,
                          T ~ AVS2),
         AVS2 = case_when(sum(AVS3)==1 ~ 0,
                          T ~ AVS3))

更新:

这是@akrun 提供的解决方案。

library(dplyr)
data %>% 
   group_by(sample.name) %>%
   mutate(across(starts_with('AVS'), ~ case_when(sum(.) == 1 ~ 0, TRUE ~ .)))

他们建议将case_when修改为~ case_when(sum(.) == 1 ~ 0L, TRUE ~ .))) 通过修改并通过在starts_with()更改“AVS”->“ASV”,我能够从我的数据集中删除单例。

这是我用来测试数据集中是否有单例的方法:

# look and see if there are singletons
#we do this by summing occurrences of ASV in PCR reps per sample
#if there is a singleton, the sum of occurrences for an ASV in a sample will be equal to one
t <- data%>% group_by(sample.name) %>% #make group
  select(-sample.pcr) %>% #remove column
  dplyr::summarise(across(.fns=sum)) # sum an ASV's occurrence for a sample, do this across the whole dataset
sum(t==1) #check how many sums were equal to one - if this is greater than 0 then we need to remove singletons

我们可以使用across将函数应用于多列

library(dplyr)
data %>% 
   group_by(sample.name) %>%
   mutate(across(starts_with('AVS'), ~ case_when(sum(.) == 1 ~ 0, TRUE ~ .)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM