Use strsplit to get last character in r

dataCruncher02 picture dataCruncher02 · Oct 16, 2014 · Viewed 12.6k times · Source

I have a file of baby names that I am reading in and then trying to get the last character in the baby name. For example, the file looks like..

Name      Sex 
Anna      F
Michael   M
David     M
Sarah     F

I read this in using

sourcenames = read.csv("babynames.txt", header=F, sep=",")

I ultimately want to end up with my result looking like..

Name   Last Initial   Sex
Michael  l             M
Sarah    h             F

I've managed to split the name into separate characters..

sourceout = strsplit(as.character(sourcenames$Name),'')

But now where I'm stuck is how to get the last letter, so in the case of Michael, how to get 'l'. I thought tail() might work but its returning the last few records, not the last character in each Name element.

Any help or advice is greatly appreciated.

Thanks :)

Answer

Rich Scriven picture Rich Scriven · Oct 16, 2014

For your strsplit method to work, you can use tail with sapply

df$LastInit <- sapply(strsplit(as.character(df$Name), ""), tail, 1)
df
#      Name Sex LastInit
# 1    Anna   F        a
# 2 Michael   M        l
# 3   David   M        d
# 4   Sarah   F        h

Alternatively, you can use substring

with(df, substring(Name, nchar(Name)))
# [1] "a" "l" "d" "h"