r - Replace symbol + and - with (+) and (-) only if they begin a string -


df$x <- gsub("[+]", "(+)", df$x) df$x<- gsub("[-]", "(-)", df$x) 

these 2 commands replace + , - (+) (-) in column though want change if starts cell.

you try

 df$x <- gsub('^\\+', '(+)',df$x) 

and

 gsub('^\\-', '(-)',df$x) 

another option using gsubfn in single step

 library(gsubfn)  gsubfn("^[+-]", list(`+` = "(+)", `-` = "(-)"), df$x)  #[1] "(+)234x"    "ab+234"     "(+)cf+43"   "(-)234+49"  "abc-23"      #[6] "(-)23ab-34" 

data

 df <- structure(list(x = c("+234x", "ab+234", "+cf+43", "-234+49",   "abc-23", "-23ab-34")), .names = "x", row.names = c(na, -6l),  class =   "data.frame") 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -