1

I have an R dataframe(df) which includes a factor column, Team

Team
Baltimore Orioles
Kansas City Chiefs
...

I just want to create a new column, nickname, which just refers to the last name

Nickname
Orioles
Chiefs

As a first stage, I have tried splitting the factor like this

df$Nickname <- strsplit(as.character(df$Team), " ")

which produces a list of character fields which I can reference thus

>df$Nickname[1]

[[1]]
[1] "Baltimore" "Orioles"

and

>str(df$Nickname[1])

List of 1
 $ : chr [1:2] "Baltimore" "Orioles"

but then I do not know how to proceed. Trying to get the length

length(df$Nickname[1])

gives 1 - which flummoxes me

2
  • 1
    What about the Boston Red Sox? Commented Sep 26, 2011 at 15:42
  • Also, you probably wanted length(df$Nickname[[1]]) or sapply(df$Nickname, length). Commented Sep 26, 2011 at 15:43

3 Answers 3

7

Use a regular expression:

text <- c("Baltimore Orioles","Kansas City Chiefs")

gsub("^.*\\s", "", text)
[1] "Orioles" "Chiefs" 

The regex searches for:

  • ^ means the start of the string
  • .* means any character, repeated
  • \\s means a single white space

gsub finds this pattern and replaces it with an empty string, leaving you with the last word of each string.

Sign up to request clarification or add additional context in comments.

Comments

4

you just need to unlist the split strings and take the last one

    full <- c("Baltimore Orioles","Kansas City Chiefs")
    getlast <- function(x){
    parts <- unlist(strsplit(x, split = " "))
    parts[length(parts)]
    }
    sapply(full,getlast)
    > Baltimore Orioles Kansas City Chiefs 
    > "Orioles"           "Chiefs" 

3 Comments

Nice, Tim. A slightly simpler version might be sapply(strsplit(full, split=" "), tail, 1).
Thanks Guys This forum is the only one where I can post a question, go brush my teeth, come back and find an answer.make a coffee and have an enhancement
Aaron - beautiful, helped me a lot.
0

How about this?

require(plyr)
ldply(df$Nickname)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.