0

A string split operation strsplit("name1.csv", "\\.")(*) returns a list: '"name1' 'csv"'.

I know that I can select only the file name before extension like so: strsplit("name1.csv", "\\.")[[1]][1] (**)

But this was selected from the returned list from (*), which has length 1.

Why is that?

Natasha Ting
  • 49
  • 1
  • 2
  • 10
  • 5
    you extract the first list element with `[[` and the first element inside that list with `[` – akrun Jul 08 '19 at 20:41
  • Is it so because splitting a string into 2 substrings produces a list of 1 character vector, which should have length of 2? – Natasha Ting Jul 08 '19 at 20:58
  • 1
    the list length is the same as the numbeer of initial elements. Suppose you have `v1 <- c("name1.csv", "name2.csv")` and then do strsplit, the length of list is 2 and the length of each element within the list is 2, 2 from which you select the first element. so it is of length 1 – akrun Jul 08 '19 at 21:01
  • This explained. Thanks! Not sure about the web of etiquettes but if you can put the comment into answer field, I can mark the question as resolved. – Natasha Ting Jul 08 '19 at 21:04
  • Thanks, that is fine. I think there must be dupes for this post – akrun Jul 08 '19 at 21:07

1 Answers1

0

The object being returned from the strsplit function is a list of character vector which can be figured out using the class command :

> class(strsplit("name1.csv", "\\."))
[1] "list"
> class(strsplit("name1.csv", "\\.")[[1]])
[1] "character"

The elements of the list can be accessed using [[ and the elements of the character vector inside the list can be accessed using [[]] [.

The object returned by strsplit is a list of length 1 consisting of a character vector of length two as seen below:

> length(strsplit("name1.csv", "\\."))
[1] 1
> length(strsplit("name1.csv", "\\.")[[1]])
[1] 2
Amol Modi
  • 311
  • 2
  • 9