Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
in R Programming by (7.3k points)
edited by

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?

1 Answer

0 votes
edited by

To remove the last n characters from every element of a vector, 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

If you wish to Learn R Programming visit this R Programming Tutorial by Intellipaat.

How to remove last n characters from every element in the R vector
by (100 points)
edited by
Dear all,
so this one worked for the last 3:
df$data = substr(df$data,1,nchar(df$data)-3)
how would it be with the first 2 positions. Like I wanna remove all "C_" from my data.frame c("C_HE_627", "C_HE_639", "C_HE_653")
by (50.2k points)
In that case you can do this:
>c("C_HE_627", "C_HE_639", "C_HE_653")->a
> sub('C_', '', a)
[1] "HE_627" "HE_639" "HE_653"

Browse Categories