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

Viewed 18

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?

1 Answers

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))
Related