r - 基于另一列的最小值和最大值并结合 r
问题描述
所以我基本上得到了一个while循环函数,它根据“percent”列中的最高百分比在“algorithm_column”中创建1,直到达到某个总百分比(90%左右)。其余未考虑的行在“algorithm_column”中的值为 0(创建 while 循环函数,该函数取下一个最大值,直到满足条件)
我想根据循环函数找到的内容来显示“时间间隔”列的最小和最大时间(最小值是 1 的开始位置,最大值是带 1 的最后一行,0 超出范围) . 然后最后从中创建一个时间间隔。
因此,如果我们有以下代码,我想在另一列中创建,让我们说“total_time”从最小时间 09:00(这是算法列中 1 开始的位置)到 11:15 的计算,这构成了一个时间间隔02:15 小时添加到“total_time”列。
algorithm
# pc4 timeinterval stops percent idgroup algorithm_column
#1 5464 08:45:00 1 1.3889 1 0
#2 5464 09:00:00 5 6.9444 2 1
#3 5464 09:15:00 8 11.1111 3 1
#4 5464 09:30:00 7 9.7222 4 1
#5 5464 09:45:00 5 6.9444 5 1
#6 5464 10:00:00 10 13.8889 6 1
#7 5464 10:15:00 6 8.3333 7 1
#8 5464 10:30:00 4 5.5556 8 1
#9 5464 10:45:00 7 9.7222 9 1
#10 5464 11:00:00 6 8.3333 10 1
#11 5464 11:15:00 5 6.9444 11 1
#12 5464 11:30:00 8 11.1111 12 0
我有多个 pc4 组,因此它应该查看每个组并分别计算每个组的 total_time。
我得到了这个功能,但如果这是我需要的,我有点卡住了。
test <- function(x) {
ind <- x[["algorithm$algorithm_column"]] == 0
Mx <- max(x[["timeinterval"]][ind], na.rm = TRUE);
ind <- x[["algorithm$algorithm_column"]] == 1
Mn <- min(x[["timeinterval"]][ind], na.rm = TRUE);
list(Mn, Mx) ## or return(list(Mn, Mx))
}
test(algorithm)
解决方案
这是一个dplyr
解决方案。
library(dplyr)
algorithm %>%
mutate(tmp = cumsum(c(0, diff(algorithm_column) != 0))) %>%
filter(algorithm_column == 1) %>%
group_by(pc4, tmp) %>%
summarise(first = first(timeinterval),
last = last(timeinterval)) %>%
select(-tmp)
## A tibble: 1 x 3
## Groups: pc4 [1]
# pc4 first last
# <int> <fct> <fct>
#1 5464 09:00:00 11:15:00
数据。
algorithm <- read.table(text = "
pc4 timeinterval stops percent idgroup algorithm_column
1 5464 08:45:00 1 1.3889 1 0
2 5464 09:00:00 5 6.9444 2 1
3 5464 09:15:00 8 11.1111 3 1
4 5464 09:30:00 7 9.7222 4 1
5 5464 09:45:00 5 6.9444 5 1
6 5464 10:00:00 10 13.8889 6 1
7 5464 10:15:00 6 8.3333 7 1
8 5464 10:30:00 4 5.5556 8 1
9 5464 10:45:00 7 9.7222 9 1
10 5464 11:00:00 6 8.3333 10 1
11 5464 11:15:00 5 6.9444 11 1
12 5464 11:30:00 8 11.1111 12 0
", header = TRUE)
推荐阅读
- python - 如何从python列表中删除字符
- php - 如何将我的 SQL 查询连接到 PHP 中的重置按钮?
- jquery - Jquery find 识别不正确的元素
- swift - 如何在当前循环结束时停止设置为无限循环的avaudioplayernode
- html - 在 ERB 中使用 link_to 生成的 HREF 不可点击
- ruby-on-rails - 如何在一次只查询几个时找到数据库中元素的索引?
- javascript - 如何在 vue.js 中识别何时完成获取
- python - 在熊猫中按组顺序计算差异
- elasticsearch - Elasticsearch Group By Aggregation with Filtering Performance
- python - 如何从命令行对输入参数进行单元测试?