只提取_之后的数字,中间有数字

时间:2018-05-23 22:11:39

标签: r string unique substr

所以我有两列看起来像这样:

    V1                                V2
    ENSP00000222573_N559D             ENSG00000105855
    ENSP00000222573_N559D             ENSG00000105855
    ENSP00000267853_E337*             ENSG00000108239
    ENSP00000299441_R1672P,R1672G     ENSG00000127415
    ENSP00000334642_K277N.            ENSG00000134324
    ENSP00000342952_N585R             ENSG00000134324

首先,我需要第一列提取_之后的所有字母/符号 所以结果需要看起来像这样:

V1      V2
ND      ENSG00000105855
ND      ENSG00000105855
E*      ENSG00000108239
RP,RG   ENSG00000127415
KN      ENSG00000134324
NR      ENSG00000134324

然后我想过滤这样只有当V1和... V2一起加倍,它们被过滤掉了。 所以最终结果将是:

  V1      V2
    ND      ENSG00000105855
    E*      ENSG00000108239
    RP,RG   ENSG00000127415
    KN      ENSG00000134324
    NR      ENSG00000134324

2 个答案:

答案 0 :(得分:2)

使用的解决方案。 dat2是最终输出。

library(tidyverse)

dat2 <- dat %>%
  separate(V1, into = c("Re", "V1"), sep = "_") %>%
  select(-Re) %>%
  mutate(V1 = str_replace_all(V1, "[0-9]*", "")) %>%
  distinct(V1, V2, .keep_all = TRUE)
dat2
#      V1              V2
# 1    ND ENSG00000105855
# 2    E* ENSG00000108239
# 3 RP,RG ENSG00000127415
# 4   KN. ENSG00000134324
# 5    NR ENSG00000134324

数据

dat <- read.table(text = "V1                                V2
    ENSP00000222573_N559D             ENSG00000105855
                  ENSP00000222573_N559D             ENSG00000105855
                  'ENSP00000267853_E337*'             ENSG00000108239
                  'ENSP00000299441_R1672P,R1672G'     ENSG00000127415
                  'ENSP00000334642_K277N.'            ENSG00000134324
                  ENSP00000342952_N585R             ENSG00000134324",
                  header = TRUE, stringsAsFactors = FALSE)

答案 1 :(得分:1)

选项可以使用sapplystrsplit作为:

sapply(df, function(x){
 sapply(strsplit(x, split = "_"), function(y){
   if(length(y)<2){
     y
   } else {
     gsub("[0-9]+","",y[2])
   }
 })
  }) %>% as.data.frame() %>% distinct()


#      V1              V2
# 1    ND ENSG00000105855
# 2    E* ENSG00000108239
# 3 RP,RG ENSG00000127415
# 4   KN. ENSG00000134324
# 5    NR ENSG00000134324

数据:

df <- read.table(text = 
 "V1                                V2
ENSP00000222573_N559D             ENSG00000105855
ENSP00000222573_N559D             ENSG00000105855
ENSP00000267853_E337*             ENSG00000108239
ENSP00000299441_R1672P,R1672G     ENSG00000127415
ENSP00000334642_K277N.            ENSG00000134324
ENSP00000342952_N585R             ENSG00000134324",
stringsAsFactors = FALSE, header = TRUE)