0

Consider e.g. the following data frame:

data <- matrix(c(12, 6, 13, 15, 2, 7, 7, 14), nrow = 4)
data <- as.data.frame(data)
Variable 1 Variable 2
12 2
6 7
13 7
15 14

Suppose that the values of the Variable 2 are instances of two categories; category 1 (values < 10) and category 2 (values >= 10).

How could I replace the second column by the category of its value? The resulting data frame would be:

Variable 1 Variable 2 (Category)
12 Category 1
6 Category 1
13 Category 1
15 Category 2
Shawn Hemelstrand
  • 2,676
  • 4
  • 17
  • 30
mathslover
  • 215
  • 1
  • 5

2 Answers2

1
library(tidyverse) 

data %>% 
  mutate(across(V2, ~ if_else(.x >= 10, "Category 2", "Category 1")))

     V1 V2        
  <dbl> <chr>     
1    12 Category 1
2     6 Category 1
3    13 Category 1
4    15 Category 2
Chamkrai
  • 5,912
  • 1
  • 4
  • 14
0

alternatively with data.table

library(data.table)

data <- matrix(c(12, 6, 13, 15, 2, 7, 7, 14), nrow = 4)
data <- as.data.table(data)

format_cat <- function(x){
  case_when(
  x < 10 ~ 'Category 1',
  x >=10 ~ 'Category 2'
  )
}

data[, V2 := format_cat(V2)]

Created on 2023-02-25 with reprex v2.0.2

   V1         V2
1: 12 Category 1
2:  6 Category 1
3: 13 Category 1
4: 15 Category 2
jkatam
  • 2,691
  • 1
  • 4
  • 12