[R] strange behaviour with loops and lists

peter dalgaard pdalgd at gmail.com
Sun May 19 19:02:53 CEST 2013


On May 19, 2013, at 18:08 , Liviu Andronic wrote:

> Dear all,
> I encountered this strange behaviour with loops and lists. Consider this:
> xl <- list()
> for(i in 5:7){##loop over numeric vector
>    xl[[i]] <- rnorm(i)
> }
>> xl
> [[1]]
> NULL
> 
> [[2]]
> [1] -0.4448192 -1.3395014
> 
> [[3]]
> [1]  1.3214195 -1.2968560 -0.6327795
> 
> 
> The above lists contained a NULL element for some reason. While the code below:
> xl <- list()
> for(i in as.character(2:3)){##loop over character vector
>    xl[[i]] <- rnorm(i)
> }
>> xl
> $`2`
> [1] -1.139506  2.894280
> 
> $`3`
> [1] 0.0599175 1.0793515 0.4296049
> 
> 
> This resulting list contains no extraneous elements. Is this normal? Why?

(The first example really had 2:3, not 5:7, right?)

The essential bit is that to assign to the 2nd element of a list, it needs to have at least two elements:

> x <- list()
> x[[2]] <- 123
> x
[[1]]
NULL

[[2]]
[1] 123

assigning to an element with a specific name just requires there is an element of that name:

> x[["2"]] <- 321
> x
[[1]]
NULL

[[2]]
[1] 123

$`2`
[1] 321

In both cases, x will be extended if needed, so that the required element exists. Notice that there is no relation between the name and the number of a list element; e.g., x[["2"]] is the 3rd element in the above example.


-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list