Home > Software engineering >  Get Certain Patterns of Chracters in a String in R
Get Certain Patterns of Chracters in a String in R

Time:11-18

How can I in R predefine patterns that I would like to keep in a string a then in a column of a data frame?

g <- c("3 kk120", "3 1121", "1 170", "1 kk5")

# I want to get
c("3 kk", "3 1", "1 1", "1 kk")

enter image description here

CodePudding user response:

I am not quite sure if I understand you but, after replacing two digits (kk) into one (X) you can use substr(). Then you can replace back the previous one as follows,

sub("X","kk",substr(sub("kk","X",g),1,3))

gives,

# [1] "3 kk" "3 1"  "1 1"  "1 kk"
  •  Tags:  
  • r
  • Related