Mathica
Mathica

Reputation: 1303

how to append certain row of different matrices to construct a new dataframe in R

I have a list of 10 matrices called mat.list, each is a 3 by 20 matrix, mat1 to mat10.
I want to make a dataframe whose rows are the first row of each matrix. hence a 10 by 20 dataframe.

for(i in 1:10){
  my.df <- rbind(my.df , mat.list[[i]][i,])
}

this is not doing what I want. it appends many more rows. how can I do this job?

Upvotes: 1

Views: 21

Answers (1)

akrun
akrun

Reputation: 887691

Loop over the list with lapply, extract the first row and rbind the list elements

my.df <- do.call(rbind, lapply(mat.list, function(x) x[1, , drop = FALSE]))

Or use head

my.df <- do.call(rbind, lapply(mat.list, head, 1))

Upvotes: 1

Related Questions