34

I'd like to split a vector of character strings (people's names) into two columns (vectors). The problem is some people have a 'two word' last name. I'd like to split the first and last names into two columns. I can slit out and take the first names using the code below but the last name eludes me. (look at obs 29 in the sample set below to get an idea as the Ford has a "last name" of Pantera L that must be kept together)

What I have attempted to do so far;

x<-rownames(mtcars)
unlist(strsplit(x, " .*"))

What I'd like it to look like:

            MANUF       MAKE
27          Porsche     914-2
28          Lotus       Europa
29          Ford        Pantera L
30          Ferrari     Dino
31          Maserati    Bora
32          Volvo       142E

7 Answers 7

32

The regular expression rexp matches the word at the start of the string, an optional space, then the rest of the string. The parenthesis are subexpressions accessed as backreferences \\1 and \\2.

rexp <- "^(\\w+)\\s?(.*)$"
y <- data.frame(MANUF=sub(rexp,"\\1",x), MAKE=sub(rexp,"\\2",x))
tail(y)
#       MANUF      MAKE
# 27  Porsche     914-2
# 28    Lotus    Europa
# 29     Ford Pantera L
# 30  Ferrari      Dino
# 31 Maserati      Bora
# 32    Volvo      142E
0
21

For me, Hadley's colsplit function in the reshape2 package is the most intuitive for this purpose. Joshua's way is more general (ie can be used wherever a regex could be used) and flexible (if you want to change the specification); but the colsplit function is perfectly suited to this specific setting:

library(reshape2)
y <- colsplit(x," ",c("MANUF","MAKE"))
tail(y)
#      MANUF      MAKE
#27  Porsche     914-2
#28    Lotus    Europa
#29     Ford Pantera L
#30  Ferrari      Dino
#31 Maserati      Bora
#32    Volvo      142E
2
  • 1
    +1 Really interesting, since I had assumed colsplit will return more than three columns in this case. How wrong I was.
    – Andrie
    Nov 28, 2011 at 19:21
  • I spent 50 minutes to find the solution to this extremely simple task. I am really surprised by how complicated it is to solve such simple tasks.
    – Seymour
    Feb 8, 2020 at 15:45
13

Here are two approaches:

1) strsplit. This approach uses only functions in the core of R and no complex regular expressions. Replace the first space with a semicolon (using sub and not gsub), strsplit on the semicolon and then rbind it into a 2 column matrix:

mat <- do.call("rbind", strsplit(sub(" ", ";", x), ";"))
colnames(mat) <- c("MANUF", "MAKE")

2) strapply in gsubfn package Here is a one-liner using strapply in the gsubfn package. The two parenthesized portions of the regular expression capture the desired first and second columns respectively and the function (which is specified in formula notation -- its the same as specifying function(x, y) c(MANUF = x, MAKE = y)) grabs them and adds names. The simplify=rbind argument is to used to turn it into a matrix as in the prior solution.

library(gsubfn)
mat <- strapply(x, "(\\S+)\\s+(.*)", ~ c(MANUF = x, MAKE = y), simplify = rbind)

Note: In either case a "character" matrix, mat, is returned. If a data frame of "character" columns is desired then add this:

DF <- as.data.frame(mat, stringsAsFactors = FALSE)

Omit the stringsAsFactors argument if "factor" columns are wanted.

1
  • I just checked back here. I actually wound up liking your #1 solution the best of any supplied. Thanks and sorry for the later return. Dec 24, 2011 at 19:09
9

Yet another way of doing it:

str_split from stringr will handle the split, but returns it in a different form (a list, like strsplit does). Manipulating into the correct form is straightforward though.

library(stringr)
split_x <- str_split(x, " ", 2)
(y <- data.frame(
  MANUF = sapply(split_x, head, n = 1),
  MAKE  = sapply(split_x, tail, n = 1)
))

Or, as Hadley mentioned in the comments, with str_split_fixed.

y <- as.data.frame(str_split_fixed(x, " ", 2))
colnames(y) <- c("MANUF", "MAKE")
y
1
  • 1
    It's interesting to note that this answer + hadley's comment is related to the colsplit solution because colsplit uses str_split_fixed.
    – Xu Wang
    Nov 28, 2011 at 20:32
0

If you can do pattern and group matching, I'd try something like this (untested):

\s+(.*)\s+(.*)
1
  • 6
    Just so you know, regex's in R work a little differently. At the very least, you'd need to add another \ in front of each s, just to avoid an error.
    – joran
    Nov 28, 2011 at 18:13
0

You can also use tidyr::extract after converting your vector into a data frame first - I think this would also be the more modern version of older solutions with reshape2

library(tidyr)

## first convert into a data frame
x <- data.frame(x = rownames(mtcars))

## use extract, and for example Joshua's regex
res <- extract(x, col = x, into = c("MANUF", "MAKE"), regex = "^(\\w+)\\s?(.*)$")

head(res)
#>     MANUF       MAKE
#> 1   Mazda        RX4
#> 2   Mazda    RX4 Wag
#> 3  Datsun        710
#> 4  Hornet    4 Drive
#> 5  Hornet Sportabout
#> 6 Valiant
-2

I think searching for [^\s]+ would work. Untested.

Not the answer you're looking for? Browse other questions tagged or ask your own question.