PeregHer
PeregHer

Reputation: 13

How to get the first element of a strsplit in R

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

Answers (4)

akrun
akrun

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"

data

string <- 'AAAAAA.BBBB'

Upvotes: 1

s_baldur
s_baldur

Reputation: 33488

You could also use some simple regex:

sub('\\..*', '', 'AAAAAA.BBBB')
[1] "AAAAAA"

Upvotes: 0

Lue Mar
Lue Mar

Reputation: 472

try this :

variable = unlist(strsplit('AAAAAA.BBBB', '\\.'))[1]

Upvotes: 1

Ronak Shah
Ronak Shah

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

Related Questions