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?
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.
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.
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.
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.
I think you are getting the 1 argument form of [
. If you do lapply(myList, `[`, i =, j = 1)
it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With