1

I have a matrix where the first column is the ID of the samples, the columns 2 to 15 are the observed presences of 14 fish species, and the columns 16 to 29 are the predicted presences of the same 14 species.

I need to build 14 matrices (1 per species) with 3 columns each: first column = ID of the samples (e.g. column 1 of the original matrix), 2nd column = observed presence of the species, 3rd column = predicted presence of the species.

Lets say that A is the ID of my samples:

A<-c(1,2,3,4,5,6,7,8,9,10)

B are the observed values for my species

B<-replicate(14,rnorm(10))

C are the predicted values for my species

C<-replicate(14,rnorm(10))

So I have the matrix "data":

data<-cbind(A, B, C)

I want to do something like this

A1<-cbind(data[,1],data[,2],data[,16]) A2<-cbind(data[,1],data[,3],data[,17])

etc.. until having A1 to A14 matrices, one for each species. I suspect that I need to use the lapply function but I am lost. Can anyone help me?

Thanks!!

user2963185
  • 23
  • 1
  • 7

1 Answers1

0

We can use lapply to create a list of matrices by looping through the sequence of columns

lst <- lapply(seq_len(ncol(B)), function(i) cbind(A, B= B[,i], C=C[,i]))
names(lst) <- paste0("A", seq_along(lst))

It is better to keep it in a list instead of creating multiple objects in the global environment. But, if we need it anyway

list2env(lst, .GlobalEnv)
akrun
  • 874,273
  • 37
  • 540
  • 662