# [R] Question on list objects

Joshua Wiley jwiley.psych at gmail.com
Sat Jan 8 18:59:53 CET 2011

```Hi Ron,

Here you go.

Cheers,

Josh

dat <- matrix(1:9,3)
ldat <- list(dat, dat, dat)
ldat[] == dat

## Or
lapply(1:3, function(x) dat)
## which is similar in spirit to
output <- vector("list", 3)
for(i in 1:3) {
output[[i]] <- dat
}

list1 <- list2 <- vector("list", length=2)

for(i in 1:2) {
list1[[i]] <- matrix(rnorm(15), 3)
list2[[i]] <- matrix(rnorm(15), 3)
}

lapply(1:2, function(x) {list1[[x]] + list2[[x]]})

## This can be done more simply
lapply(1:2, function(x) {matrix(rnorm(15), 3) + matrix(rnorm(15), 3)})

On Sat, Jan 8, 2011 at 3:26 AM, Ron Michael <ron_michael70 at yahoo.com> wrote:
> Hi, I have 2 questions on list object:
>
> 1. Suppose I have a matrix like:
> dat <- matrix(1:9,3)
>
> Now I want to replicate this entire matrix 3 times and put entire result in a list object. Means, if "res" is the resulting list then I should have:
>
> res[]=dat, res[]=dat, res[]=dat
>
> How can I do that in the easilest manner?
>
> 2. Suppose I have 2 list objects:
> list1 <- list2 <- vector("list", length=2)
> for(i in 1:2) {
>   list1[[i]] <- matrix(rnorm(15), 3)
>   list2[[i]] <- matrix(rnorm(15), 3)
>  }
>
> How can I add these 2 list objects? I have tried with just list1+list2, however it is generating some error.
>
> Would be grateful for any help.
>
> Thanks,
>
>
>        [[alternative HTML version deleted]]
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> and provide commented, minimal, self-contained, reproducible code.
>
>

--
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/

```