Reputation: 13
I want to keep the first element of a string and store it in a variable.
In Python it would be word = 'AAAAAA.BBBB'.split('.')[0]
but I can't find how to do it in R.
Thanks
Upvotes: 1
Views: 2064
Reputation: 887048
We can use str_split
library(stringr)
str_split(string, fixed("."))[[1]][1]
#[1] "AAAAAA"
Or using trimws
trimws(string, whitespace = "\\..*")
#[1] "AAAAAA"
string <- 'AAAAAA.BBBB'
Upvotes: 1
Reputation: 33488
You could also use some simple regex
:
sub('\\..*', '', 'AAAAAA.BBBB')
[1] "AAAAAA"
Upvotes: 0
Reputation: 388907
You can use
string <- 'AAAAAA.BBBB'
result <- strsplit(string, '.', fixed = TRUE)[[1]][1]
#[1] "AAAAAA"
You can also do this without splitting with regex removing everything after a period (.
)
sub('\\..*', '', string)
Upvotes: 0