dplyr:折叠可能不存在的行

dplyr:折叠可能不存在的行,r,dataframe,dplyr,R,Dataframe,Dplyr,我正在处理GTF格式的生物序列数据。以下是一个简单的格式示例: start stop type name 1 90 exon transcript_1_exon_1 12 15 start_codon transcript_1_exon_1 100 160 exon transcript_1_exon_2 190 250 exon transcript_1

我正在处理GTF格式的生物序列数据。以下是一个简单的格式示例:

start   stop   type         name 
1       90     exon         transcript_1_exon_1
12      15     start_codon  transcript_1_exon_1
100     160    exon         transcript_1_exon_2
190     250    exon         transcript_1_exon_3
217     220    stop_codon   transcript_1_exon_3
我正试图将外显子转换成它们的蛋白质序列。然而,外显子的某些部分不是蛋白质编码。这通过存在一行来表示,
type
字段设置为
start\u codon
stop\u codon

我想将这些功能的开始和结束分别移动到它们自己的列中,如下所示:

start   stop  type         name                 start_codon  stop_codon
1       90    exon         transcript_1_exon_1  12           NA
100     160   exon         transcript_1_exon_2  NA           NA
190     250   exon         transcript_1_exon_3  NA           220
但是,我不知道如何在R中实现这一点。我最近使用的
dplyr
是:

gtf3 <- gtf2 %>% group_by(feature_name) %>% summarise(
  start_codon = ifelse(sum(type == "start_codon") != 0, start[type == "start_codon"], NA),
  stop_codon = ifelse(sum(type == "stop_codon") != 0, stop[type == "stop_codon"], NA))
gtf3%分组依据(功能名称)%%>%摘要(
start_codon=ifelse(sum(type==“start_codon”)!=0,start[type==“start_codon”],NA),
停止密码子=ifelse(和(类型==“停止密码子”)!=0,停止[类型==“停止密码子”],NA))
但这给了我以下错误:
计算错误:“closure”类型的对象不可子集。

当起始/终止密码子存在时,我如何将它们的起始和结束分别移动到它们自己的列中?

这里有一种方法:

df1 %>% filter(type=="exon") %>%
  left_join(df1 %>% 
              filter(type=="start_codon") %>% 
              select(-type,-stop),by="name",suffix = c("","_codon")) %>%
  left_join(df1 %>%  
              filter(type=="stop_codon") %>% 
              select(-type,-start),by="name",suffix = c("","_codon"))

#   start stop type                name start_codon stop_codon
# 1     1   90 exon transcript_1_exon_1          12         NA
# 2   100  160 exon transcript_1_exon_2          NA         NA
# 3   190  250 exon transcript_1_exon_3          NA        220