Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value of strsplit

Tags:

r

In the following example

x = strsplit('30 min', ' ')

The return value as the docs state is

A list of the same length as x, the i-th element of which contains the vector of splits of x[i].

I would expect x[[1]] to return 30 and x[[2]] to return min

However x[[1]][1] returns 30 and x[[1]][2] returns min.

What is the explanation for this?

like image 209
cosmosa Avatar asked Dec 14 '25 17:12

cosmosa


2 Answers

The result you get is because you are splitting only one element (this answer expands on comments initially made by @R. Schifini).

x <- '30 min'
length(x)
#> [1] 1
strsplit(x, ' ')
#> [[1]]
#> [1] "30"  "min"

Try splitting a vector of 3 strings and you'll get a list containing 3 vectors, each containing the split result for a single string.

x <- c( '30 min', '15 min', '20 30 min etc')
length(x)
#> [1] 3
strsplit(x, ' ')
#> [[1]]
#> [1] "30"  "min"
#> 
#> [[2]]
#> [1] "15"  "min"
#> 
#> [[3]]
#> [1] "20"  "30"  "min" "etc"
like image 69
markdly Avatar answered Dec 16 '25 10:12

markdly


The explanation is that strsplit expects a vector of input strings, each of which will be split into an array of strings, which are returned in the form of a list. If you only provide this one string, it will be treated like it was the single entry of a vector. Thus, the result is a list with one entry (x[[1]]) and it's split contents (x[[1]][1] and x[[1]][2]), as you've described.

Just use x <- unlist(strsplit('30 min', ' ')) or x <- strsplit('30 min', ' ')[[1]] and you'll get a character-vector, where x[1] returns 30 and x[2] returns min.

like image 30
alex_jwb90 Avatar answered Dec 16 '25 10:12

alex_jwb90



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!