Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string vector at whitespace

I have the following vector:

tmp3 <- c("1500 2", "1500 1", "1510 2", "1510 1", "1520 2", "1520 1", "1530 2", 
"1530 1", "1540 2", "1540 1")

I would like to just retain the second number in each of the atoms of this vector, so it would read:

c(2,1,2,1,2,1,2,1,2,1)
like image 616
Zak Avatar asked Nov 04 '09 22:11

Zak


People also ask

How do you split a string in whitespace?

You can split a String by whitespaces or tabs in Java by using the split() method of java. lang. String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces.

Can you split a string array?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


3 Answers

There's probably a better way, but here are two approaches with strsplit():

as.numeric(data.frame(strsplit(tmp3, " "))[2,])
as.numeric(lapply(strsplit(tmp3," "), function(x) x[2]))

The as.numeric() may not be necessary if you can use characters...

like image 136
Shane Avatar answered Oct 18 '22 03:10

Shane


One could use read.table on textConnection:

X <- read.table(textConnection(tmp3))

then

> str(X)
'data.frame':   10 obs. of  2 variables:
 $ V1: int  1500 1500 1510 1510 1520 1520 1530 1530 1540 1540
 $ V2: int  2 1 2 1 2 1 2 1 2 1

so X$V2 is what you need.

like image 42
Marek Avatar answered Oct 18 '22 02:10

Marek


It depends a little bit on how closely your actual data matches the example data you've given. I you're just trying to get everything after the space, you can use gsub:

gsub(".+\\s+", "", tmp3)
[1] "2" "1" "2" "1" "2" "1" "2" "1" "2" "1"

If you're trying to implement a rule more complicated than "take everything after the space", you'll need a more complicated regular expresion.

like image 11
SchaunW Avatar answered Oct 18 '22 01:10

SchaunW