R - how to replace parts of variable strings withi

2019-01-17 11:24发布

问题:

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?

回答1:

Use gsub

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

gsub("t", "", dat)
[1] "es"    "esing" "esen"  "esen"  "bles"  "esen" 


回答2:

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