I have a matrix which would be a matrix of factors if R supported them. I want to print the matrix with the factor names, rather than ints, for readability. Using indexing loses the matrix structure. Is there a tidier workaround than the one I have below?
care_types = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 5L, 5L, 5L,
6L, 5L, 4L, 1L, 6L, 4L, 4L, 1L, 1L, 5L, 1L, 2L, 1L, 1L, 6L, 5L,
1L, 2L, 1L, 5L, 5L, 2L, 1L, 5L, 2L, 3L, 1L, 3L, 6L, 1L, 5L, 6L,
5L, 5L, 1L, 5L, 6L, 4L, 5L, 3L, 1L, 2L, 2L, 1L, 3L, 5L, 5L), dim = c(10L,
6L))
care_type_names = c('M', 'F', 'O', 'I', 'H', 'C')
# This loses the dimensions
care_type_names[care_types]
# This works but is clunky
apply(care_types, 1:2, function(v) {return(care_type_names[[v]])})
# This doesn't work and I don't follow why
apply(care_types, 1:2, ~care_type_names[[.x]])
1
You could write an anonymous function with (x)
as in
apply(care_types, 1:2, (x) care_type_names[[x]])
which returns
[1,] "M" "H" "M" "F" "O" "I"
[2,] "M" "H" "M" "M" "C" "H"
[3,] "M" "H" "H" "H" "M" "O"
[4,] "M" "C" "M" "H" "H" "M"
[5,] "M" "H" "F" "F" "C" "F"
[6,] "M" "I" "M" "M" "H" "F"
[7,] "M" "M" "M" "H" "H" "M"
[8,] "M" "C" "C" "F" "M" "O"
[9,] "M" "I" "H" "O" "H" "H"
[10,] "M" "I" "M" "M" "C" "H"
The result is a matrix of type character:
> apply(care_types, 1:2, (x) care_type_names[[x]]) |> typeof()
[1] "character"