我如何将R数据框中的值替换为它们的类别?[duplicate]

whhtz7ly  于 2023-03-05  发布在  其他
关注(0)|答案(2)|浏览(96)
    • 此问题在此处已有答案**:

Add column which contains binned values of a numeric column(3个答案)
Categorize numeric variable into group/ bins/ breaks(4个答案)
Convert continuous numeric values to discrete categories defined by intervals(2个答案)
7天前关闭。
例如,考虑以下 Dataframe :

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

| 变量1|变量2|
| - ------|- ------|
| 十二|第二章|
| 六个|七|
| 十三|七|
| 十五|十四|
假设变量2的值是两个类别的示例;类别1(值〈10)和类别2(值〉= 10)。
如何将第二列替换为值的类别?生成的数据框将是:
| 变量1|变量2(类别)|
| - ------|- ------|
| 十二|第1类|
| 六个|第1类|
| 十三|第1类|
| 十五|第二类|

lymgl2op

lymgl2op1#

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
n9vozmp4

n9vozmp42#

或者使用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)]

创建于2023年2月25日,使用reprex v2.0.2

V1         V2
1: 12 Category 1
2:  6 Category 1
3: 13 Category 1
4: 15 Category 2

相关问题