jmbarbone/markExtra

Correct `autoplot_table_mosaic()` table names

Closed this issue · 0 comments

autoplot_table_mosaic() uses psych::table2df() because I'm too lazy to write that myself. The problem is that psych::table2df() expects numeric row and column names in the table. Need to change these to numeric (probably factor()) and then rename the columns afterwards.

x <- as.table(
  matrix(
    c(1, 2, 3, 4),
    nrow = 2,
    dimnames = list(a = list(TRUE, FALSE), b = list(TRUE, FALSE))
  )
)

psych::table2df(x)
#> Warning in psych::table2df(x): NAs introduced by coercion

#> Warning in psych::table2df(x): NAs introduced by coercion
#>    X1 X2
#> 1  NA NA
#> 2  NA NA
#> 3  NA NA
#> 4  NA NA
#> 5  NA NA
#> 6  NA NA
#> 7  NA NA
#> 8  NA NA
#> 9  NA NA
#> 10 NA NA
# there's a call to as.numeric(rownames(x)), as.numeric(colnames(x))
psych::table2df
#> function (x, count = NULL, labs = NULL) 
#> {
#>     if (!is.null(count)) {
#>         xm.df <- bigtable2matrix(x, count, labs)
#>     }
#>     else {
#>         n <- sum(x)
#>         nrows <- dim(x)[1]
#>         ncol <- dim(x)[2]
#>         rowval <- as.numeric(rownames(x))
#>         colval <- as.numeric(colnames(x))
#>         xm <- matrix(NaN, nrow = n, ncol = 2)
#>         k <- 1
#>         for (rows in 1:nrows) {
#>             for (cols in 1:ncol) {
#>                 case <- x[rows, cols]
#>                 if (case > 0) {
#>                   for (cases in 1:case) {
#>                     xm[k, 1] <- rowval[rows]
#>                     xm[k, 2] <- colval[cols]
#>                     k <- k + 1
#>                   }
#>                 }
#>             }
#>         }
#>         if (!is.null(labs)) 
#>             colnames(xm) <- labs
#>         xm.df <- data.frame(xm)
#>     }
#>     return(xm.df)
#> }
#> <bytecode: 0x000002c311e892b8>
#> <environment: namespace:psych>


# copy table and change the names
y <- x
rownames(y) <- as.numeric(factor(rownames(x)))
colnames(y) <- as.numeric(factor(colnames(x)))
df <- psych::table2df(y)

# change back
colnames(df) <- names(dimnames(x))
df
#>    a b
#> 1  2 2
#> 2  2 1
#> 3  2 1
#> 4  2 1
#> 5  1 2
#> 6  1 2
#> 7  1 1
#> 8  1 1
#> 9  1 1
#> 10 1 1

Created on 2022-07-27 by the reprex package (v2.0.1)