Convenient fucntions to implement conversion between tidy table and named matrix.
mat_df(m)
df_mat(df, row, col, value)
A matrix
A data.frame with at least 3 columns, one for row name, one for column name, and one for values. The names for column and row should be unique.
Unquoted expression of column name for row
Unquoted expression of column name for column
Unquoted expression of column name for values
For mat_df
, a data.frame.
For df_mat
, a named matrix.
mm = matrix(c(1:8,NA),ncol = 3,dimnames = list(letters[1:3],LETTERS[1:3]))
mm
#> A B C
#> a 1 4 7
#> b 2 5 8
#> c 3 6 NA
tdf = mat_df(mm)
tdf
#> row col value
#> 1 a A 1
#> 2 b A 2
#> 3 c A 3
#> 4 a B 4
#> 5 b B 5
#> 6 c B 6
#> 7 a C 7
#> 8 b C 8
#> 9 c C NA
mat = df_mat(tdf,row,col,value)
setequal(mm,mat)
#> [1] TRUE
tdf %>%
setNames(c("A","B","C")) %>%
df_mat(A,B,C)
#> A B C
#> a 1 4 7
#> b 2 5 8
#> c 3 6 NA