[R] apply one list to another one

Rui Barradas ruipbarradas at sapo.pt
Fri May 4 02:20:16 CEST 2012


Hello,


Hui Du wrote
> 
> Hi All,
> 
> Suppose I have the following codes:
> 
> x = data.frame(A = rnorm(20), B = rnorm(20), C = rnorm(20))
> a = list()
> a[["1.1"]] = x
> a[["1.2"]] = x
> 
> b = list()
> b[["1.1"]] = c("A", "B")
> b[["1.2"]] = c("B", "C")
> 
> 
> Now I want to apply b to a like this, for each element of 'a', only select
> the corresponding columns listed in 'b'. For example, after that
> operation,
> 
> a[["1,1"]] become subset(a[["1.1"]], select = c("A", "B"))
> 
> a[["1,2"]] become subset(a[["1.1"]], select = c("B", "C"))
> 
> Do you know how to do it without looping?
> 
> Thanks.
> 
> 
> HXD
> 
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help@ 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.
> 

If it's a list and you want to avoid a loop, think about lapply or similar.
(Tip: you don't want sapply.)


?lapply
lapply(names(a), function(i) subset(a[[i]], select = b[[i]]))

It's your code, but "lapplied" to all elements of your objects.
Hope this helps,

Rui Barradas


--
View this message in context: http://r.789695.n4.nabble.com/apply-one-list-to-another-one-tp4607386p4607453.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list