Yulia Kentieva
Yulia Kentieva

Reputation: 720

How to replace numeric values in a dataframe by categorical labels in R?

How to replace numeric values of this dataframe:

df <- data.frame(num = 1:10, num2=-8:1, num3=2:11)
df <- as.matrix(df)

into cut labels?

df_categ <- cut(df, breaks = c(-Inf, 2, 4, Inf), labels=c("DOWN", "NORM", "UP"))

cut gives a list. But I need to substitute my numeric elements in the original df

Upvotes: 2

Views: 433

Answers (1)

akrun
akrun

Reputation: 887991

We could use [] to convert it to original attributes

df[] <- as.character(df_categ)

Instead of converting the 'df' to a matrix, we could use the original data.frame

library(dplyr)
df <- df %>%
   mutate(across(everything(), cut, 
         breaks = c(-Inf, 2, 4, Inf), labels = c("DOWN", "NORM", "UP")))
df
    num num2 num3
1  DOWN DOWN DOWN
2  DOWN DOWN NORM
3  NORM DOWN NORM
4  NORM DOWN   UP
5    UP DOWN   UP
6    UP DOWN   UP
7    UP DOWN   UP
8    UP DOWN   UP
9    UP DOWN   UP
10   UP DOWN   UP

Or use lapply from base R

df[] <- lapply(df,  cut, breaks = c(-Inf, 2, 4, Inf),
        labels = c("DOWN", "NORM", "UP"))

Upvotes: 3

Related Questions