Home > database >  How to remove matching characters between two columns
How to remove matching characters between two columns

Time:06-11

I have a dataframe df. I want to gsub values of REF and the Effect_allele until one or the other is completely removed or left with distinct characters.

df <- structure(list(CHROM = c("chr1", "chr1", "chr1", "chr1", "chr1"
), POS_GRCh38 = c(109655507L, 145830809L, 168201814L, 172359627L, 
204533386L), REF = c("CAAA", "CT", "C", "TA", "TTCTGAAACAGGG"
), Effect_allele = c("C", "C", "CA", "T", "TC"), Effect_size = c(0.0266, 
0.0126, 0.0718, 0.0655, 0.1345)), row.names = c(234L, 240L, 243L, 
244L, 249L), class = "data.frame")

The result I want is:

CHROM POS_GRCh38         REF Effect_allele Effect_size
chr1  109655507          AAA                 0.0266
chr1  145830809          T                   0.0126
chr1  168201814                       A      0.0718
chr1  172359627          A            T      0.0655
chr1  204533386 TCTGAAACAGGG          C      0.1345

I can create an index like below and execute gsub, but I was wondering if there is a simpler solution.

max.values <- apply(cbind(nchar(dfS$REF), nchar(df$Effect_allele)),1, which.max)
min.values <- apply(cbind(nchar(df$REF), nchar(df$Effect_allele)),1, which.min)

CodePudding user response:

yo could write a small recursion function to do the task:

fun <- function(a, b){
  a1 <- substr(a,1,1)
  b1 <- substr(b, 1, 1)
  d <- asplit(cbind(a, b), 1)
  ifelse(a1==b1, Recall(str_remove(a,a1), str_remove(b, b1)), d)
}

df[c('REF', 'Effect_allele')] <-  do.call(rbind, fun(df$REF, df$Effect_allele))
df
    CHROM POS_GRCh38          REF Effect_allele Effect_size
234  chr1  109655507          AAA                    0.0266
240  chr1  145830809            T                    0.0126
243  chr1  168201814                          A      0.0718
244  chr1  172359627            A                    0.0655
249  chr1  204533386 TCTGAAACAGGG             C      0.1345
  •  Tags:  
  • r
  • Related