Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all the string elements after first space

Tags:

split

r

If I have a with character elements divided by space, how can i create 2 vectors ,one of everything before the space and one after the space. One important thing is that some characters have multiple spaces

Example: say my vector is called vec1

(head) vec 1
'rrrt rrr' 'tttt   gg'    'tt pp' 'hhhh      k'

As you can see some words are divided by multiple spaces, I would like to have 2 vectors like this

head(vector1)
'rrrt' 'tttt' 'tt' 'hhhh'
head(vector2)
'rrr' 'gg' 'pp' 'k'

As you can see the first vector has everything before the first space and the second vector has everything after the space but without the actual spaces.

like image 589
idf4floor Avatar asked Jan 23 '26 17:01

idf4floor


1 Answers

We can use sub with pattern \\S+ (one or more non-white space) followed by one or more white space to remove the prefix or we can remove the white space followed by non white space to remove the suffix.

sub("^\\S+\\s+", '', vec1)
sub("\\s+\\S+$", '', vec1)

Or use read.table to convert this to a data.frame with two columns and then extract those columns

d1 <- read.table(text= vec1, header=FALSE, stringsAsFactors=FALSE)
v1 <- d1[,1]
v2 <- d1[,2]

Or another option is strsplit to split it to a list and then extract the list elements.

lst <- strsplit(vec1, "\\s+")
v1 <- sapply(lst ,`[`, 1)
v2 <- sapply(lst, `[`, 2)

data

vec1 <- c("rrrt rrr", "tttt   gg", "tt pp", "hhhh      k")
like image 96
akrun Avatar answered Jan 26 '26 08:01

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!