Coerce Input to Character Matrix with Meaningful Column Names
Source:R/char_matrix.R
char_matrix.RdConverts various R object types, such as vectors, factors, data frames, data tables, tibbles, and lists, into a character matrix, preserving or assigning column names intelligently.
Usage
char_matrix(y, cname = NULL)
# Default S3 method
char_matrix(y, cname = NULL)
# S3 method for class 'factor'
char_matrix(y, cname = NULL)
# S3 method for class 'list'
char_matrix(y, cname = NULL)
# S3 method for class 'data.frame'
char_matrix(y, cname = NULL)
# S3 method for class 'data.table'
char_matrix(y, cname = NULL)
# S3 method for class 'matrix'
char_matrix(y, cname = NULL)Details
The transformation of the R objects into a character matrix is
done through base::as.character and using base::as.matrix when the
method is defined for the object type. For lists, NA are appended to the
elements that have an object length less than the maximum object length.
See also
base::as.matrix data.table::data.table tibble::tibble
Examples
char_matrix(y = 1:3)
#> [,1]
#> [1,] "1"
#> [2,] "2"
#> [3,] "3"
char_matrix(y = factor(x = c("a", "b", "c")), cname = "ex_name")
#> ex_name
#> [1,] "a"
#> [2,] "b"
#> [3,] "c"
char_matrix(y = data.frame(a = 1:3, b = letters[1:3]))
#> a b
#> [1,] "1" "a"
#> [2,] "2" "b"
#> [3,] "3" "c"
char_matrix(y = list(one = 1:3, two = 4:6))
#> one two
#> [1,] "1" "4"
#> [2,] "2" "5"
#> [3,] "3" "6"