0

My matrix consists of numbers:

set.seed(2016)
A <- matrix(rnorm(4,250,50), nrow = 2, ncol = 2, byrow = TRUE)

I want to discretize them into 3 classes: lmh <- c("low", "moderate", "high")

low: <30
medium: 30 - 300
high >300

Is this possible without converting the matrix into a data.frame and without using a loop?

This seems like a very easy task but I could not find anything.

Marcus Campbell
  • 2,746
  • 4
  • 22
  • 36
user1607
  • 531
  • 7
  • 28
  • @9Jan i need both – user1607 May 01 '18 at 20:11
  • 1
    See `?cut`. `cut(A, breaks = c(-Inf, 30, 300, Inf), labels = c("low", "moderate", "high"))`. Assign the result to `A[] <- as.character(cut(...))` to keep the dimensions and produce a `character` matrix. Alternately `result = matrix(as.character(cut(...), nrow = nrow(A))` if you don't want to overwrite `A`. – Gregor Thomas May 01 '18 at 20:12
  • 1
    the output should be a matrix – user1607 May 01 '18 at 20:14

1 Answers1

1
library(dplyr)
case_when(A < 30   ~ 'low'
        , A <= 300 ~ 'medium'
        , T        ~ 'high') %>% 
  `dim<-`(dim(A))

Or

A %>% 
  cut(breaks = c(-Inf, 30, 300, Inf), labels = c("low", "med", "high")) %>% 
  `dim<-`(dim(A))
IceCreamToucan
  • 28,083
  • 2
  • 22
  • 38