36

I have a dataframe df:

var1 var2
"test" "testing"
"esten" "etsen"
"blest" "estten"

Now I want to delete all "t" inside df to get:

var1 var2
"es" "esing"
"esen" "esen"
"bles" "esen"

How do I do that?

daroczig
  • 28,004
  • 7
  • 90
  • 124
user670186
  • 2,588
  • 6
  • 37
  • 55

2 Answers2

49

Use gsub

dat <- c("test", "testing", "esten", "etsen", "blest", "estten")

gsub("t", "", dat)
[1] "es"    "esing" "esen"  "esen"  "bles"  "esen" 
Chase
  • 67,710
  • 18
  • 144
  • 161
  • Works great for me! Just be aware that gsub's first argument is a _regular expression pattern_ and not a plain string. – Tapper Jan 15 '19 at 16:14
32

You can do this with gsub and using sapply to apply it per variable:

df <- data.frame( 
    var1 = c("test","esten","blest"),
    var2 = c("testing","etsen","esttem"))

df2 <- as.data.frame(sapply(df,gsub,pattern="t",replacement=""))
df2
  var1  var2
1   es esing
2 esen  esen
3 bles  esem
Sacha Epskamp
  • 46,463
  • 20
  • 113
  • 131
  • I think you need to wrap a `data.frame()` around the `sapply` to get back to a data.frame, right? – Chase Mar 30 '11 at 13:59