Search code examples
rerase

how to erase several characters in a cell?


I would like to erase characters "(B)" in the code column, so then I could do "summarise" the 'stock_needed'. My data looks like this.

  code   stock_need 
(B)1234    200          
(B)5678    240      
1234       700          
5678       200          
0123       200          

to be like this.

code   stock_need 
1234       200          
5678       240      
1234       700          
5678       200          
0123       200  

How could these "(B)" erased? Thanx in advance


Solution

  • What are other patterns your data has? If it's always "(B)" you can do

    sub("\\(B\\)", "", df$code)
    #[1] "1234" "5678" "1234" "5678" "0123"
    

    Or if it could be any character do

    sub("\\([A-Z]\\)", "", df$code)
    

    You could also extract only the numbers from Code

    sub(".*?(\\d+).*", "\\1", df$code)
    

    You might want to wrap output of sub in as.numeric or as.integer to get numeric/integer output.


    We can also use readr

    readr::parse_number(df$code)