crumbly crumbly - 1 year ago 54
R Question

Removing characters from column value and adding a new letter

I have the following data frame df1. I want to remove "/" from all values in column x2 and add letter v at the end of each value in x2.

df1
x1 x2
1 aa/bb/cc
2 ff/bb/cc
3 uu/bb/cc


Resulting df2

df2
x1 x2
1 aabbccv
2 ffbbccv
3 uubbccv

Answer Source

You can use gsub to remove the / and paste0 to add the v in each row:

df2 <- transform(df1, x2 = paste0(gsub("/", "", x2, fixed = TRUE), "v"))
df2
#  x1      x2
#1  1 aabbccv
#2  2 ffbbccv
#3  3 uubbccv