Split column by last word in sentence

YARQ (Another regular expression question).

How I would like to divide the following into two columns, making sure that the last column contains the last word in the sentence, and the first column contains everything else.

x <- c("This is a test",
       "Testing 1,2,3 Hello",
       "Foo Bar",
       "Random 214274(%*(^(* Sample",
       "Some Hyphenated-Thing"
       )

So what I get:

col1                         col2
this is a                    test
Testing 1,2,3                Hello
Foo                          Bar
Random 214274(%*(^(*         Sample
Some                         Hyphenated-Thing
+5
source share
4 answers

It looks like a job to look forward. We will find spaces followed by things that are not spaces.

split <- strsplit(x, " (?=[^ ]+$)", perl=TRUE)
matrix(unlist(split), ncol=2, byrow=TRUE)

     [,1]                   [,2]              
[1,] "This is a"            "test"            
[2,] "Testing 1,2,3"        "Hello"           
[3,] "Foo"                  "Bar"             
[4,] "Random 214274(%*(^(*" "Sample"          
[5,] "Some"                 "Hyphenated-Thing"
+9
source

Here you can use strsplit:

do.call(rbind,
  lapply(
    strsplit(x," "),
    function(y)
      cbind(paste(head(y,length(y)-1),collapse=" "),tail(y,1))
    )
)

Or an alternative implementation using sapply

t(
  sapply(
    strsplit(x," "),
    function(y) cbind(paste(head(y,length(y)-1),collapse=" "),tail(y,1))
  )
)

Result:

     [,1]                   [,2]              
[1,] "This is a"            "test"            
[2,] "Testing 1,2,3"        "Hello"           
[3,] "Foo"                  "Bar"             
[4,] "Random 214274(%*(^(*" "Sample"          
[5,] "Some"                 "Hyphenated-Thing"
+4
source

, "" - ( \\w \\d, ):

col_one = gsub("(.*)(\\b[[\\w\\d]+)$", "\\1", x, perl=TRUE)
col_two = gsub("(.*)(\\b[[\\w\\d]+)$", "\\2", x, perl=TRUE)

:

> col_one
[1] "This is a "            "Testing 1,2,3 "        "Foo "                 
[4] "Random 214274(%*(^(* "
> col_two
[1] "test"   "Hello"  "Bar"    "Sample"
+1

This may not be entirely accurate for you, but in case someone wonders how to do this in python :

#col1:
print line.split(" ")[:-1]

#col2:
print line.split(" ")[-1]

Note that col1 will be printed as a list, which you can make in a line like this:

#col1:
print " ".join(line.split(" ")[:-1])
0
source

All Articles