How to extract the last 2 components in a vector

Hi everyone, I'm trying to extract the last 2 components in this vector, however, I keep failing so far. Could you please help?

address_1 <- c("Sorrento Road", " Dalkey" , " South Co. Dublin")
address_2 <- c("Ailesbury Road", " Ballsbridge", " Dublin 4", " South Dublin City")

I want to get a result of the last 2 strings in these vectors (i.e.: "Dalkey", "South Co. Dublin" from address_1 and " Dublin 4", " South Dublin City" from address_2

Thanks in advance!

For each vector, you can use code like the following. Is that what you want?

tail(address_2, 2)
[1] " Dublin 4"          " South Dublin City"
1 Like

Thanks FJCC for your reply. However, it's not working for my scenario. I have a column where it contains all the vectors (example in screenshot). I want to get only the last two items from these vectors. I tried with different functions: lapply, split, tail,... it didn't work.
image

Your first post provided data, and FJCC kindly showed how to complete your requested task on that data, but your follow up message indicates that your data is different. Therefore please take a moment to make a reproducible example, such that it presents the issue you wish to solve.

I would really encourage you to review the following guide, FAQ: Tips for writing R-related questions. For example, the guide emphasizes asking coding questions with formatted code-chunks and a reprex, which would make it easier for people who want to help you to pick up your issue and attempt to run with a solution.

1 Like

Thank you! I am very new to R, so still learning to get familiar with how to write codes and reproducing the issue. Will have a look at that FAQ.

Hi welcome to the forum.

You may also find this helpful.
FAQ: How to do a minimal reproducible example ( reprex ) for beginners

A handy way to supply some sample data is the dput() function. In the case of a large dataset something like dput(head(mydata, 100)) should supply the data we need.

1 Like

Thanks a lot for that, jrkrideau. I definitely need that.

And by the way, I've found the solutions for my issue. I used the str_match() and it works the way I wanted. I don't know yet how to share it here. There are a lot for me to learn, I just need a starting point.

Thanks everyone!

Hi @Suzziebrillia

Without seeing the code I think your approach is okay but something like tail() is likely to be a lot less cumbersome. If you supply a bit of sample data someone here should be able to give some pointers.

Good luck with R.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.