[R] strange behaviour with loops and lists

arun smartpink111 at yahoo.com
Sun May 19 18:28:45 CEST 2013


Hi,
xl<- vector("list",7)
for(i in 5:7){##loop over numeric vector
     xl[[i]] <- rnorm(i)
 }
 xl
#[[1]]
#NULL
#
#[[2]]
#NULL
#
#[[3]]
#NULL
#
#[[4]]
#NULL
#
#[[5]]
#[1]  0.3266762  0.4316069  1.2290551 -0.6725783  1.6159861
#
#[[6]]
#[1] -2.8560618 -0.5694743 -0.7325862  1.6786160  0.3883842 -0.3991854
#
#[[7]]
#[1] -1.22443607  0.66940158  0.97476608 -0.85964961  0.06331827 -0.40658831
#[7]  0.24824287

xlNew<- vector("list",4)
for(i in as.character(2:3)){##loop over character vector
    xlNew[[as.numeric(i)]] <- rnorm(i)
}

xlNew
#[[1]]
#NULL
#
#[[2]]
#[1] -2.155804  1.780388
#
#[[3]]
#[1]  0.4192816 -1.0142512 -0.2125988
#
#[[4]]
#NULL
A.K.




----- Original Message -----
From: Liviu Andronic <landronimirc at gmail.com>
To: "r-help at r-project.org Help" <r-help at r-project.org>
Cc: 
Sent: Sunday, May 19, 2013 12:08 PM
Subject: [R] strange behaviour with loops and lists

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?

Thanks,
Liviu

-- 
Do you know how to read?
http://www.alienetworks.com/srtest.cfm
http://goodies.xfce.org/projects/applications/xfce4-dict#speed-reader
Do you know how to write?
http://garbl.home.comcast.net/~garbl/stylemanual/e.htm#e-mail

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list