[R] apply one list to another one

David Winsemius dwinsemius at comcast.net
Fri May 4 04:51:24 CEST 2012


On May 3, 2012, at 7:39 PM, 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"))

I'm assuming the is a typo and you wanted
  a[["1,2"]] become subset(a[["1.2"]], select = c("B", "C"))

>
> Do you know how to do it without looping?

using lapply is a loop construct but maybe it won't feel that way:

 > lapply( names(a), function(x) subset(a[[x]],  select=b[[x]]) )
[[1]]
               A           B
1  -0.660594340 -0.44402746
2   0.926022768  0.50906870
3  -0.357588460 -0.10657540
4   0.226316328  1.96415323
5   0.143330486 -0.89655890
6  -0.307193955 -1.10708473
7  -0.904927213  2.01289010
8  -1.922708953  0.74302970
9   1.008833376  0.90442422
10  1.095004836  1.23202474
11 -0.568905764  0.20946675
12  0.621113819  0.25753637
13  0.001997838  0.41691655
14 -0.206525640  0.94883919
15 -0.665738673  1.29442907
16 -1.225075753  0.49222447
17  0.224294111 -0.51241903
18 -0.170286569  0.09245769
19  0.396839258  0.23253796
20  0.645889199  0.52546631

[[2]]
              B           C
1  -0.44402746 -0.05013952
2   0.50906870  0.32247682
3  -0.10657540 -0.54740895
4   1.96415323  0.63823531
5  -0.89655890  0.54520142
6  -1.10708473 -0.14625567
7   2.01289010 -0.97021834
8   0.74302970  0.49252268
9   0.90442422  0.30610560
10  1.23202474 -0.52001742
11  0.20946675 -0.96469545
12  0.25753637  0.22606727
13  0.41691655  0.48728976
14  0.94883919 -0.99520018
15  1.29442907  0.60930763
16  0.49222447 -0.23321555
17 -0.51241903 -0.72746372
18  0.09245769 -1.96009906
19  0.23253796 -0.14303924
20  0.52546631  2.12944010

--
David Winsemius, MD
Heritage Laboratories
West Hartford, CT



More information about the R-help mailing list