首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >R:如何在我的数据帧的所有列中删除tidyverse组中的单例?

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

Stack Overflow用户
提问于 2020-11-07 05:27:15
回答 1查看 108关注 0票数 1

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

到目前为止,我已经能够用3个ASV在小规模上做到这一点,但我的方法要求我写出每个ASV的名称。这对我不起作用,因为我的数据集有9000个ASV。我需要一个更好的方法来删除单例。

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

代码语言:javascript
运行
复制
#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提供的解决方案。

代码语言:javascript
运行
复制
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”,我能够从我的数据集中删除单例。

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

代码语言:javascript
运行
复制
# 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
EN

回答 1

Stack Overflow用户

发布于 2020-11-07 05:29:12

我们可以使用across在多个列上应用函数

代码语言:javascript
运行
复制
library(dplyr)
data %>% 
   group_by(sample.name) %>%
   mutate(across(starts_with('AVS'), ~ case_when(sum(.) == 1 ~ 0, TRUE ~ .)))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64721804

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档