Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use `[` correctly with (l|s)apply to select a specific column from a list of matrices?

Tags:

r

Consider the following situation where I have a list of n matrices (this is just dummy data in the example below) in the object myList

mat <- matrix(1:12, ncol = 3) myList <- list(mat1 = mat, mat2 = mat, mat3 = mat, mat4 = mat) 

I want to select a specific column from each of the matrices and do something with it. This will get me the first column of each matrix and return it as a matrix (lapply() would give me a list either is fine).

sapply(myList, function(x) x[, 1]) 

What I can't seem able to do is use [ directly as a function in my sapply() or lapply() incantations. ?'[' tells me that I need to supply argument j as the column identifier. So what am I doing wrong that this does't work?

> lapply(myList, `[`, j = 1) $mat1 [1] 1  $mat2 [1] 1  $mat3 [1] 1  $mat4 [1] 1 

Where I would expect this:

$mat1 [1] 1 2 3 4  $mat2 [1] 1 2 3 4  $mat3 [1] 1 2 3 4  $mat4 [1] 1 2 3 4 

I suspect I am getting the wrong [ method but I can't work out why? Thoughts?

like image 863
Gavin Simpson Avatar asked Oct 29 '10 16:10

Gavin Simpson


People also ask

How do you select a column in a matrix?

When we create a matrix in R, its column names are not defined but we can name them or might import a matrix that might have column names. If the column names are not defined then we simply use column numbers to extract the columns but if we have column names then we can select the column by name as well as its name.

How do I select a specific column in a matrix in R?

You should therefore use a comma to separate the rows you want to select from the columns. For example: my_matrix[1,2] selects the element at the first row and second column. my_matrix[1:3,2:4] results in a matrix with the data on the rows 1, 2, 3 and columns 2, 3, 4.

How do you get a column from a matrix in R?

To get a specific column of a matrix, specify the column number preceded by a comma, in square brackets, after the matrix variable name. This expression returns the required row as a vector.

What is the syntax of the Apply () in R explain with example?

apply() functionapply() takes Data frame or matrix as an input and gives output in vector, list or array. Apply function in R is primarily used to avoid explicit uses of loop constructs. It is the most basic of all collections can be used over a matrice. The simplest example is to sum a matrice over all the columns.


1 Answers

I think you are getting the 1 argument form of [. If you do lapply(myList, `[`, i =, j = 1) it works.

like image 134
frankc Avatar answered Sep 18 '22 15:09

frankc