Passes from a stacked (= tidy) data.frame to a matrix. tidy_to_matrix() is an alias of this function.

stack_to_matrix(
  my_df,
  col_to_row,
  col_to_col,
  col_value = NULL,
  sparse = FALSE
)

Arguments

my_df

data.frame you want to transform in matrix

col_to_row

character vector of the name of the data.frame column you want to put into matrix rows

col_to_col

character vector of the name of the data.frame column you want to be as columns in matrix

col_value

(optional, default = NULL) character vector indicating the name of a column coding the values that will be put in the matrix

sparse

(optional, default = FALSE) logical indicating whether to return a sparse matrix (if TRUE requires tidytext package)

Value

a matrix with given col_to_row column in rows and col_to_col

column in columns. If some cells are not present in the data.frame (e.g. some species not present at some sites), the matrix will have a NA value.

See also

matrix_to_stack() for the reverse operation

Examples

example = data.frame("sites" = c(rep("1", 3), rep("2", 2)),
 "species" = c("A", "B", "C", "B", "D"),
  "abundance" = c(0.33, 0.33, 0.33, 0.4, 0.6))

mat = stack_to_matrix(example, "sites", "species", "abundance")
mat
#>      species
#> sites    A    B    C   D
#>     1 0.33 0.33 0.33  NA
#>     2   NA 0.40   NA 0.6