[R] applying cbind (or any function) across all components in a list

David L Carlson dcarlson at tamu.edu
Fri May 25 16:28:09 CEST 2012


This should give you what you want and it is simpler than the earlier
version:

a1<-  array(1:6, dim=c(2,3))
a2<-  array(7:12, dim=c(2,3))
l1<-  list(a1,a2)

a3<-  array(1:4, dim=c(2,2))
a4<-  array(5:8, dim=c(2,2))
l2<-  list(a3,a4)

pattern <- cbind(c(1, 2, 2, 3), c(1, 1, 2, 2))
lnew <- lapply(1:length(l1), function(i) 
  (l1[[i]][,pattern[,1]]+l2[[i]][,pattern[,2]])/2)
lnew

If all the information from your several posts had been included in the
original request, we could have responded more quickly. 

----------------------------------------------
David L Carlson
Associate Professor of Anthropology
Texas A&M University
College Station, TX 77843-4352


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Hans Thompson
> Sent: Thursday, May 24, 2012 5:19 PM
> To: r-help at r-project.org
> Subject: Re: [R] applying cbind (or any function) across all components
> in a list
> 
> Yes. This gives me:
> 
>      [,1] [,2] [,3] [,4]
> [1,]    1    2    3    4
> [2,]    2    3    4    5
>      [,1] [,2] [,3] [,4]
> [1,]    6    7    8    9
> [2,]    7    8    9   10
> 
> BUT, how can I have it still within components like
> 
> [[1]]
>      [,1] [,2] [,3] [,4]
> [1,]    1    2    3    4
> [2,]    2    3    4    5
> 
> [[2]]
>      [,1] [,2] [,3] [,4]
> [1,]    6    7    8    9
> [2,]    7    8    9   10
> 
> How should I have phrased my question to be specific to this result?
> 
> Thanks.
> 
> --
> View this message in context: http://r.789695.n4.nabble.com/applying-
> cbind-or-any-function-across-all-components-in-a-list-
> tp4631128p4631258.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> 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