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?
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"
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.
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