# [R] What is going on?

Ben Bolker bolker at ufl.edu
Wed Feb 11 20:43:31 CET 2009

```
The problem is that strsplit is designed to work on a *vector* of
characters (your example is a length-1 vector of characters), each
of which might end up being split into a character vector of different
lengths, so it returns its results as a *list* the same length as
the original character vector: in this case a list of length 1.

> str(l)
List of 1
\$ : chr [1:2] "1" "2"

length(l) is 1; length(l[]) is 2.

Ben Bolker

Paul Johnston-6 wrote:
>
> Ok, so I'm new to R, but this is driving me crazy.  In this example, I
> am trying to process each element in a list.
>
> <code>
> s = "1,2"
> l = strsplit(s, ",", fixed=TRUE)
> print("BEGIN")
> n = length(l)
> i = 1
> while (i <= n) {
>   x = l[[i]]
>   print(paste("x:", class(x), x))
>   print("BEFORE PRINT")
>   print(x)
>   print("AFTER PRINT")
>   i = i + 1
> }
> </code>
>
> <actual output>
>      [exec]  "BEGIN"
>      [exec]  "x: character 1" "x: character 2"
>      [exec]  "BEFORE PRINT"
>      [exec]  "1" "2"
>      [exec]  "AFTER PRINT"
>      [exec]  "END"
>      [exec]  TRUE
> </actual output>
>
> <expected output>
>      [exec]  "BEGIN"
>      [exec]  "x: character 1"
>      [exec]  "BEFORE PRINT"
>      [exec]  "1"
>      [exec]  "AFTER PRINT"
>      [exec]  "x: character 2"
>      [exec]  "BEFORE PRINT"
>      [exec]  "2"
>      [exec]  "AFTER PRINT"
>      [exec]  "END"
>      [exec]  TRUE
> </expected output>
>
> What *basic* concept am I missing here?  The same thing happens with
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>

--
View this message in context: http://www.nabble.com/What-is-going-on--tp21962284p21962681.html
Sent from the R help mailing list archive at Nabble.com.

```