0
$\begingroup$

I have a data frame like this

> head(a[1:2,1:4])
   Tumor_Sample_Barcode Chromosome Position End_Position
1:                   A1       chr4 90169866     90169866
2:                   A1      chr11 60235747     60235747
    > dim(a)
[1] 753655    134
>
> unique(a$Tumor_Sample_Barcode)
 [1] "A1"  "A10" "A11" "A12" "A13" "A14" "A15" "A16" "A17" "A18" "A19" "A2"  "A20" "A21" "A22" "A23" "A24" "A25" "A26" "A27" "A28"
[22] "A29" "A3"  "A30" "A31" "A32" "A33" "A4"  "A5"  "A6"  "A7"  "A8"  "A9" 

I want to change a$Tumor_Sample_Barcode from A1:A21 to res1:res21 but I don't how to do that

$\endgroup$

2 Answers 2

8
$\begingroup$

I think you are looking for gsub function:

a$Tumor_Sample_Barcode <- gsub("A","res",a$Tumor_Sample_Barcode)

If you prefer, you can use the str_replace_all function from stringr package. But it tooks a little bit more time than gsub:

Dummy data

seq = as.factor(paste0("A",1:21))
library(data.table)
dt <- data.table(Barcode = rep(seq,10000),
                 Value = rnorm(210000))

Test of gsub vs str_replace_all

> system.time(dt$Barcode <- gsub("A","res",dt$Barcode))
   user  system elapsed 
  0.077   0.000   0.077 

> system.time(dt$Barcode <- str_replace_all(dt$Barcode,"A","res"))
   user  system elapsed 
  0.123   0.004   0.126 
```
$\endgroup$
7
$\begingroup$

Other options:

  • Drop 1st character and prefix with "res"
  • We get 5x speed up if we set fixed = TRUE for gsub.
microbenchmark::microbenchmark(
  # dc37 answer
  gsub("A","res", dt$Barcode),
  stringr::str_replace_all(dt$Barcode, "A", "res"),
  # other options
  paste0("res", substring(dt$Barcode, 2)),
  gsub("A","res",dt$Barcode, fixed = TRUE),

  # bench set up
  check = "identical", 
  unit = "relative"
  )

Unit: relative
                                             expr      min       lq     mean   median       uq      max neval
                     gsub("A", "res", dt$Barcode) 5.171682 5.132816 4.283014 5.033968 3.177772 2.545173   100
 stringr::str_replace_all(dt$Barcode, "A", "res") 6.914598 6.870849 5.747396 6.728126 4.809257 3.518024   100
          paste0("res", substring(dt$Barcode, 2)) 1.983757 1.991876 1.779557 1.968488 1.480892 3.415619   100
       gsub("A", "res", dt$Barcode, fixed = TRUE) 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000   100
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.