[英]R - Max, Min function using specific value from a different column
Working on my own side project, I have a smaller dataframe containing only 2 columns that was subsetted from a larger dataframe. 在我自己的副项目上,我有一个较小的数据框,其中仅包含2个列,这些列是从较大的数据框派生的。
The 2 columns I am working on is "Lap.." and "Timestamp..s.". 我正在处理的两列是“ Lap ..”和“ Timestamp..s。”。
I want to get the minimum timestamp and maximum timestamp from a specific lap number. 我想从特定的单圈数中获得最小时间戳和最大时间戳。
Right now my focus is having a hard coded value for the specific lap number. 现在,我的重点是为特定的单圈数提供一个硬编码值。
Here is my code: 这是我的代码:
time_df <- csv_to_Table[c("Lap..", "Timestamp..s." )]
#output data to csv to make sure that it is correct
write.csv(time_df, file = "data/lap_timestamp.csv")
output$time_test <- renderText({
max(time_df$Timestamp..s.) - min(time_df$Timestamp..s.)
})
The above code will display the total time that I was driving on the track. 上面的代码将显示我在赛道上驾驶的总时间。
However, when I read the max and min documentation it doesn't mention about having an extra criteria to filter on. 但是,当我阅读max和min文档时,并没有提及要过滤的其他条件。 Seeing dplyr library does contain a filter, I gave it a try, but still no luck.
看到dplyr库确实包含过滤器,我尝试了一下,但还是没有运气。
output$time_test <- renderText({
(max(time_df$Timestamp..s.) %>% filter(time_df$Lap.. == 1)) - (min(time_df$Timestamp..s.) %>% filter(time_df$Lap.. == 1))
})
Test data is located here: https://pastebin.com/GZvWEcXb 测试数据位于此处: https : //pastebin.com/GZvWEcXb
In the future I will want to move to having a dropdown for the lap number. 将来,我将希望转至圈数下拉列表。
Any help/hint is appreciated. 任何帮助/提示表示赞赏。
You could also use aggregate()
. 您也可以使用
aggregate()
。 If I understood you corectly your data looks like the following: 如果我完全了解您,则您的数据如下所示:
# Make up some data
set.seed(1)
df = data.frame(Lap = sample(1:10, size = 20, replace = TRUE),
Timestamp = sample(seq.POSIXt(from = ISOdate(2017,1,1), to = ISOdate(2017,06,1), by = "day"), size = 20, replace = TRUE))
Then use aggregate()
to get the min or max of each lap number: 然后使用
aggregate()
获得每个圈数的最小值或最大值:
aggregate(Timestamp ~ Lap, data = df, FUN = min)
aggregate(Timestamp ~ Lap, data = df, FUN = max)
Output: 输出:
> aggregate(Timestamp ~ Lap, data = df, FUN = min)
Lap Timestamp
1 1 2017-02-21 13:00:00
2 2 2017-04-02 14:00:00
3 3 2017-02-10 13:00:00
4 4 2017-01-29 13:00:00
5 5 2017-04-12 14:00:00
6 6 2017-04-10 14:00:00
7 7 2017-02-28 13:00:00
8 8 2017-03-04 13:00:00
9 9 2017-02-28 13:00:00
10 10 2017-01-03 13:00:00
> aggregate(Timestamp ~ Lap, data = df, FUN = max)
Lap Timestamp
1 1 2017-02-21 13:00:00
2 2 2017-04-02 14:00:00
3 3 2017-05-23 14:00:00
4 4 2017-04-21 14:00:00
5 5 2017-04-12 14:00:00
6 6 2017-04-10 14:00:00
7 7 2017-05-13 14:00:00
8 8 2017-05-06 14:00:00
9 9 2017-02-28 13:00:00
10 10 2017-01-20 13:00:00
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.