Back
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?
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 data21 foo_bar 12 bar_foo 23 apple 34 beer 4
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 data21 foo_ 12 bar_ 23 ap 34 b 4
df$data = substr(df$data,1,nchar(df$data)-3)
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.
31k questions
32.8k answers
501 comments
693 users