Skip to contents

Converts 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)

Arguments

y

An object to be converted to a character matrix. Acceptable types include vector, factor, matrix, data.frame, data.table, tibble, or list.

cname

A character vector of column names. Default is NULL, which means factors and atomic vectors will not be assigned a column name.

Value

A character matrix with meaningful column names when possible.

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"