vlangber
vlangber

Reputation: 13

Select columns from nested lists in r

I have a list with 50 elements, and each element is a 21x2 matrix. I want to pull every first column so that I will be able to multiply the first column of each 21x2 matrix by another matrix.

Example data:

     x<-replicate(50,cbind(rnorm(21,0,1),rnorm(21,1,1)))
     x<-lapply(seq(dim(x)[3]), function(i) x[ , , i])
     x[[1]]
                 [,1]       [,2]
     [1,] -1.00653872  1.2780327
     [2,] -0.30442989 -0.6854457
     [3,] -1.05715492 -0.3464085
     [4,]  0.12005815  1.1885382
     [5,]  0.93834177  1.4968285
     [6,]  0.85975400  1.3084381
     [7,]  0.91980222 -0.1580829
     [8,]  0.35785346  1.7679500
     [9,] -1.03510124  2.2865753
    [10,] -0.74853505  0.5148834
    [11,] -1.23582377  0.8514812
    [12,]  0.69546075  0.8294420
    [13,]  0.08527011  1.7080554
    [14,] -0.81635552  0.7492530
    [15,]  0.53826428 -0.3058294
    [16,]  0.16545497  0.4415540
    [17,] -0.27144363  0.8299643
    [18,]  0.02851933  1.2673526
    [19,]  1.86516449  0.3009744
    [20,] -0.46998359 -0.3232826
    [21,] -0.60222069  2.3836219

    assign <- rep(c(0,1),times=c(10,11))

If I do

    x[[1]][,1]*assign

I get what I'm looking for, but I want to be able to do this for all elements of x without a for-loop.

I tried

    alt<-lapply(x, `[[`, 1)

but this only gives the first element of the first columns, whereas I want the whole vector.

Any suggestions?

Upvotes: 1

Views: 1225

Answers (1)

Rorschach
Rorschach

Reputation: 32416

Try using split to split each matrix by columns and take the first one

sapply(x, function(mat) split(mat, col(mat))[1])

You could also try simplify2array

simplify2array(x)[,1,]

Upvotes: 1

Related Questions