r - Convert total records per species into record x species matrix -
imagine have 9 sampling records 3 species distributed such:
sp1 sp2 sp3 3 1 5 what want obtain records x species matrix, , fill 1s , 0s such:
sp1 sp2 sp3 1 0 0 1 0 0 1 0 0 0 1 0 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 the number of columns matches number of species , number of rows number of records. note each row represents unique record 1 species.
another option create row/column index, use sparsematrix library(matrix) create sparse matrix, can converted matrix of 0 , 1s as.matrix.
it not clear whether initial dataset matrix or not. assuming matrix 3 column , 1 row, column index replicating sequence of columns elements of 'm1'. should work if vector. data.frame, have use rep(seq_along(df1), unlist(df1)). then, create sparsematrix, specifying row index sequence of 'ci' , column index ('ci') , value 'x' 1.
library(matrix) ci <- rep(seq_along(m1), m1) m2 <- as.matrix(sparsematrix(seq_along(ci), ci, x=1)) colnames(m2) <- colnames(m1) m2 # sp1 sp2 sp3 # [1,] 1 0 0 # [2,] 1 0 0 # [3,] 1 0 0 # [4,] 0 1 0 # [5,] 0 0 1 # [6,] 0 0 1 # [7,] 0 0 1 # [8,] 0 0 1 # [9,] 0 0 1 a base r approach to create matrix of 0 , replace elements corresponds row/column index 1.
m2 <- matrix(0, nrow=length(ci), ncol=ncol(m1), dimnames=list(null, colnames(m1))) m2[cbind(seq_along(ci), ci)] <- 1 m2 # sp1 sp2 sp3 # [1,] 1 0 0 # [2,] 1 0 0 # [3,] 1 0 0 # [4,] 0 1 0 # [5,] 0 0 1 # [6,] 0 0 1 # [7,] 0 0 1 # [8,] 0 0 1 # [9,] 0 0 1 data
m1 <- structure(c(3l, 1l, 5l), .dim = c(1l, 3l), .dimnames = list(null, c("sp1", "sp2", "sp3")))
Comments
Post a Comment