0 votes
1 view
in R Programming by (5.2k points)

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
by (25.3k points)

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

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...