- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个大约 100 万行的大型数据集,其中有一列对每个客户记录都有一个分数。得分在 0 到 100 之间。
我想做的是高效使用评级表将分数映射到评级。每个客户都会根据客户的分数获得 1 到 15 之间的评分。
# Generate Example Customer Data
set.seed(1)
n_customers <- 10
customer_df <-
tibble(id = c(1:n_customers),
score = sample(50:80, n_customers, replace = TRUE))
# Rating Map
rating_map <- tibble(
max = c(
47.0,
53.0,
57.0,
60.5,
63.0,
65.5,
67.3,
69.7,
71.7,
74.0,
76.3,
79.0,
82.5,
85.5,
100.00
),
rating = c(15:1)
)
我想出的将评级表映射到客户评分数据的最佳代码如下。
customer_df <-
customer_df %>%
mutate(rating = map(.x = score,
.f = ~max(select(filter(rating_map, .x < max),rating))
)
) %>%
unnest(rating)
我遇到的问题是,虽然它可以工作,但效率极低。如果在上面的代码中设置 n = 100k,您可以了解需要多长时间才能工作。
customer_df
# A tibble: 10 x 3
id score rating
<int> <int> <int>
1 1 74 5
2 2 53 13
3 3 56 13
4 4 50 14
5 5 51 14
6 6 78 4
7 7 72 6
8 8 60 12
9 9 63 10
10 10 67 9
我需要加快代码速度,因为它目前需要一个多小时才能运行。我已经确定代码中的低效率是我对 purrr::map() 函数的使用。所以我的问题是如何在不使用 map() 函数的情况下复制上述结果?
谢谢!
最佳答案
customer_df$rating <- length(rating_map$max) -
cut(score, breaks = rating_map$max, labels = FALSE, right = FALSE)
这会产生相同的输出并且速度更快。在 1M 行上花费 1/20 秒,这听起来像是 >72,000 倍的加速。
这似乎是基本 R cut
函数的一个很好的用例,它将值分配给您提供的一组间隔。
cut divides the range of x into intervals and codes the values in xaccording to which interval they fall. The leftmost intervalcorresponds to level one, the next leftmost to level two and so on.
在这种情况下,您希望获得最高分的最低评分,因此从中断的长度中减去 cut
项。
编辑 -- 添加了 right = FALSE
因为您希望间隔在左侧闭合并在右侧打开。现在完全匹配您的输出;当值匹配中断时,以前有不同的结果。
关于R dplyr : How do I apply a less than/greater than mapping table across a large dataset efficiently?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73585760/
我是一名优秀的程序员,十分优秀!