根据数字的不同范围将数字映射到 R 中的分类值
Map numerics to categorical values in R, based on different ranges for the numerics
希望我的标题有意义。我有一个包含一列数值的数据框,我想使用此列创建一个新列,其中数值根据它们的值 'mapped' 到不同的桶。下面是一些测试数据,以及我目前用来解决这个问题的 rough-around-the-edges 嵌套 ifelse() 方法。我希望以一种不涉及嵌套 ifelse() 语句的更好的方式对此进行编码,因为这种方法不能很好地扩展到许多存储桶:
mydf = data.frame(strings = letters[1:10],
numerics = c(0.2, 0.4, 1.3, 5.2, 3.3, 2.1, 7.3, 1.1, 4.3, 8.3),
stringsAsFactors = FALSE)
这是我的测试数据框,这是我解决问题的嵌套 ifelse() 方法:
mydf$buckets = ifelse(mydf$numerics <= 2, 0,
ifelse(mydf$numerics <= 4, 1,
ifelse(mydf$numerics <= 5, 2,
ifelse(mydf$numerics <= 7, 3, 4))))
上面的代码所做的是将数字列中的值映射如下:
- 所有值 <2 转到 0
- 所有值 <4 转到 1
- 所有值 <5 转到 2
- 所有值 <7 转到 3
- 所有值 >= 7 到 4
这种方法不能很好地扩展到少量的存储桶。对此有任何帮助表示赞赏!谢谢,
尝试使用基础 R 中的 findInterval
函数:
findInterval(mydf$numerics,c(2,4,5,7))
[1] 0 0 0 3 1 1 4 0 2 4
我真的很喜欢在这种情况下使用 case_when
正如@tictocchoc 在评论中已经提到的那样:
suppressPackageStartupMessages(library(tidyverse))
mydf = data.frame(strings = letters[1:10],
numerics = c(0.2, 0.4, 1.3, 5.2, 3.3, 2.1, 7.3, 1.1, 4.3, 8.3),
stringsAsFactors = FALSE)
mydf %>%
mutate(buckets = case_when(
numerics < 2 ~0,
numerics < 4 ~1,
numerics < 5 ~2,
numerics < 7 ~3,
numerics >= 7 ~4
))
#> strings numerics buckets
#> 1 a 0.2 0
#> 2 b 0.4 0
#> 3 c 1.3 0
#> 4 d 5.2 3
#> 5 e 3.3 1
#> 6 f 2.1 1
#> 7 g 7.3 4
#> 8 h 1.1 0
#> 9 i 4.3 2
#> 10 j 8.3 4
希望我的标题有意义。我有一个包含一列数值的数据框,我想使用此列创建一个新列,其中数值根据它们的值 'mapped' 到不同的桶。下面是一些测试数据,以及我目前用来解决这个问题的 rough-around-the-edges 嵌套 ifelse() 方法。我希望以一种不涉及嵌套 ifelse() 语句的更好的方式对此进行编码,因为这种方法不能很好地扩展到许多存储桶:
mydf = data.frame(strings = letters[1:10],
numerics = c(0.2, 0.4, 1.3, 5.2, 3.3, 2.1, 7.3, 1.1, 4.3, 8.3),
stringsAsFactors = FALSE)
这是我的测试数据框,这是我解决问题的嵌套 ifelse() 方法:
mydf$buckets = ifelse(mydf$numerics <= 2, 0,
ifelse(mydf$numerics <= 4, 1,
ifelse(mydf$numerics <= 5, 2,
ifelse(mydf$numerics <= 7, 3, 4))))
上面的代码所做的是将数字列中的值映射如下:
- 所有值 <2 转到 0
- 所有值 <4 转到 1
- 所有值 <5 转到 2
- 所有值 <7 转到 3
- 所有值 >= 7 到 4
这种方法不能很好地扩展到少量的存储桶。对此有任何帮助表示赞赏!谢谢,
尝试使用基础 R 中的 findInterval
函数:
findInterval(mydf$numerics,c(2,4,5,7))
[1] 0 0 0 3 1 1 4 0 2 4
我真的很喜欢在这种情况下使用 case_when
正如@tictocchoc 在评论中已经提到的那样:
suppressPackageStartupMessages(library(tidyverse))
mydf = data.frame(strings = letters[1:10],
numerics = c(0.2, 0.4, 1.3, 5.2, 3.3, 2.1, 7.3, 1.1, 4.3, 8.3),
stringsAsFactors = FALSE)
mydf %>%
mutate(buckets = case_when(
numerics < 2 ~0,
numerics < 4 ~1,
numerics < 5 ~2,
numerics < 7 ~3,
numerics >= 7 ~4
))
#> strings numerics buckets
#> 1 a 0.2 0
#> 2 b 0.4 0
#> 3 c 1.3 0
#> 4 d 5.2 3
#> 5 e 3.3 1
#> 6 f 2.1 1
#> 7 g 7.3 4
#> 8 h 1.1 0
#> 9 i 4.3 2
#> 10 j 8.3 4