首页 文章

根据r中另一个数据帧中的列过滤一个数据帧中的行

提问于
浏览
1

我有一个名为df的数据帧

OC_ID           Bcode  Bcode_full Cell   Ploidy Goodness_of_fit
OC_DD_0181     LP2000  LP2000-A    56      3      0.45
OC_AD_9787     LP2003  LP2003-B    3       3      0.44
OC_GH_6227     LP2333  LP2333-S    66      3      0.89

我有另一个数据帧,如下所示,称为df2:

chr   leftPos    Tumour2_OCLLL_DD_0181_SLH.9396.fq.gz    Tumour2_OCLLL_DD_09787_SLH.9396.fq.gz   Tumour3_OCLLL_GH_6227_SLH.9396.fq.gz     Tumour4_OCLLL_GH_6632_SLH.9396.fq.gz   Tumour5_OCLLL_WH_6992_SLH.9396.fq.gz
chr1    720916  13.4031903  28.4522464  10.34087    23.4309208  16.239874
chr1    736092  3.4367155   36.7797331  6.893913    58.5773021  59.546204
chr1    818159  108.9438802 109.6452421 78.131014   90.2779596  108.265825
chr1    4105086 114.4426249 103.7466057 59.747246   48.9292758  129.91899
chr1    4140849 23.7133367  0.6939572   45.95942    53.0641442  37.893039

df2中列的名称与df中OC_ID行的名称不完全对应 . 我想创建一个只包含来自df2的那些列的数据帧,其中df1中Cell列中的值> 30,以便预期输出为

chr   leftPos    OC_DD_0181  OC_GH_6227
chr1    720916  13.4031903  10.34087
chr1    736092  3.4367155   6.893913
chr1    818159  108.9438802 78.131014
chr1    4105086 114.4426249 59.747246
chr1    4140849 23.7133367  45.95942

2 回答

  • 4

    我们得到相应的'OC_ID',其中'Cell'值大于30('nm1') . 然后使用 gsub 从'df2', grep 的列名中删除不需要的子字符串,使用'nm1'获取列索引,并从'df2'中提取这些列 .

    nm1 <-  df$OC_ID[df$Cell>30]
    nm2 <- gsub('.*(OC).*_([A-Z]{2}_\\d+).*', '\\1_\\2', names(df2))
    df2N <- df2[c(1:2,grep(paste(nm1, collapse='|'), nm2))]
    names(df2N)[3:4] <- nm2
    
  • 2

    只是为了完整性而发布我的缓慢(并且此时无关紧要)的答案 . 虽然在使用正则表达式时,akrun的答案(我赞成)看起来更优雅 .

    namevector <- as.character(df$OC_ID[df$Cell > 30])
    grepnames <- paste(namevector, collapse="|")
    indices <- grep(pattern=grepnames, names(df2))
    df3 <- df2[,c(1,2,indices)]
    df3 #output df that you requested
    

    因此,从df创建您想要的OC_ID的字符向量,并将其折叠成大量的grep模式字符串 . 匹配列的索引在df2中找到 . 使用两个第一列和任何匹配列创建Df3 .

相关问题