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)
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.
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.
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...
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With