Question: Imagine that I have 9 sampling records for three species distributed as such:

```
sp1 sp2 sp3
3 1 5

```

What I want to obtain is a records x species matrix, and fill it with 1s and 0s as 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 with the number of species and the number of rows with the number of records. Note that each row represents a unique record for one species.

Answer: 
Another option would be to create row/column index, use `sparseMatrix` from `library(Matrix)` to create a sparse matrix, which can be converted back to `matrix` of 0 and 1s with `as.matrix`.

It is not clear whether the initial dataset is `matrix` or not. Assuming that it is a `matrix` with 3 column and 1 row, we get the column index by replicating the sequence of columns with the elements of 'm1'. It should also work if it is a `vector`. For a `data.frame`, we have to use `rep(seq_along(df1), unlist(df1))`. Then, create the `sparseMatrix`, specifying the row index as the sequence of 'cI' , column index ('cI') and the value 'x' as 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 would to be to create a `matrix` of 0 and then replace the elements that corresponds to row/column index with 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")))

```
Here is another option using `stack` and `spread`

```
library(tidyr)

stackedList = stack(apply(df, 2, function(x) rep(1, x)))
out = spread(stackedList, ind, values, fill = 0)

#> out
#  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**

```
df = data.frame(sp1 = 3, sp2 = 1, sp3 = 5) 

```