How to remove the last n characters from every element in the R vector

278    Asked by Aalapprabhakaran in Salesforce , Asked on Apr 10, 2021

I am very new to R, and I could not find a simple example online on how to remove the last n characters from every element of a vector (array?)

I come from a Java background, so what I would like to do is to iterate over every element of a$data and remove the last 3 characters from every element.

How would you go about it?

Answered by Bernadette Bond

To remove the last n characters from string r, you can use the substr function from the base package as follows:

char_array = c("foo_bar","bar_foo","apple","beer")
> df = data.frame("data"=char_array,"data2"=1:4, stringsAsFactors = FALSE)
> df
     data data2
1 foo_bar 1
2 bar_foo 2
3 apple 3
4 beer 4
df$data = substr(df$data,1,nchar(df$data)-3)
> df
  data data2
1 foo_ 1
2 bar_ 2
3 ap 3
4 b 4

Your Answer

Interviews

Parent Categories