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 integers, 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]])
apply(care_types, 1:2, \(x) care_type_names[[x]])
? – Rembrandtapply(care_types, 2, \(x) care_type_names[x])
also works. – Retreatapply(care_types, 2, ...)
works and saves a lot of time compared toapply(care_types, 1:2, ...)
. You can check the benchmark part in my answer! – Enloe