我想根据切分标准在另一列中返回具有匹配条件的值。如果变量中的剪切分数不可用,我想为第一次和第二次剪切获取最接近的较大值,并为第三次剪切获取最接近的最小值。这是数据集的快照:
ids <- c(1,2,3,4,5,6,7,8,9,10)
scores.a <- c(512,531,541,555,562,565,570,572,573,588)
scores.b <- c(12,13,14,15,16,17,18,19,20,21)
data <- data.frame(ids, scores.a, scores.b)
> data
ids scores.a scores.b
1 1 512 12
2 2 531 13
3 3 541 14
4 4 555 15
5 5 562 16
6 6 565 17
7 7 570 18
8 8 572 19
9 9 573 20
10 10 588 21
cuts <- c(531, 560, 571)
我想获取score.b
与第一个切割分数相对应的值,即13
. 然后,抓取第二个cut( 560
)score对应的score.b值,但它不在score.a中,所以我想获取score.a值562
(最接近larger
于560
),对应的值为16
. 最后,对于第三个切割分数 ( 571
),我想得到 18,这是与第三个切割分数最接近的smaller
值 ( 570
)的对应值。
这是我想得到的。
scores.b
cut.1 13
cut.2 16
cut.3 18
有什么想法吗?谢谢
data %>%
mutate(cts = Hmisc::cut2(scores.a, cuts = cuts)) %>%
group_by(cts) %>%
summarise( mn = min(scores.b),
mx = max(scores.b)) %>%
slice(-c(1,4)) %>% unlist() %>% .[c(3,4,6)] %>%
data.frame() %>%
magrittr::set_colnames("scores.b") %>%
magrittr::set_rownames(c("cut.1", "cut.2", "cut.3"))
scores.b
cut.1 13
cut.2 16
cut.3 18
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句