R中具有数据框的每一行的最小值和最大值
Posted
技术标签:
【中文标题】R中具有数据框的每一行的最小值和最大值【英文标题】:Min and max for each row with dataframe in R 【发布时间】:2020-12-23 16:40:26 【问题描述】:我需要计算几个参加在线测试的人的处理时间。因此,对于每个人来说,都有许多时间戳(每个任务一个时间戳)。处理的持续时间是根据最小和最大日期值之间的时间差来计算的。以下示例有效 (student_1),但仅在没有缺失值时有效(student_2 和 student_3)。有什么想法吗?
library(anytime)
number <- c(1, 2, 3)
uniquename <- c("student_1", "student_2", "student_3")
timestamp_1 <- c(anytime("2020-02-25T12:42:56.476Z"),NA,anytime("2020-02-25T10:05:22.388Z"))
timestamp_2 <- c(anytime("2020-02-25T12:51:22.388Z"),anytime("2020-02-25T12:51:22.388Z"),NA)
timestamp_3 <- c(anytime("2020-02-25T13:00:45.042Z"),anytime("2020-02-25T13:00:45.042Z"),NA)
timestamp_4 <- c(anytime("2020-02-25T13:31:48.073Z"),anytime("2020-02-25T13:31:48.073Z"),NA)
timestamp_5 <- c(anytime("2020-02-25T14:22:57.103Z"),anytime("2020-02-25T15:00:00Z"),anytime("2020-02-25T14:05:00Z"))
df3 <- data.frame(number,
uniquename,
timestamp_1,
timestamp_2,
timestamp_3,
timestamp_4,
timestamp_5)
df3$date_min <- apply(df3[3:7], 1, FUN=min)
df3$date_max <- apply(df3[3:7], 1, FUN=max)
df3$date_min <- anytime(df3$date_min)
df3$date_max <- anytime(df3$date_max)
df3$diff <- difftime(df3$date_min, df3$date_max, units = "mins")
df3$diff <- round(df3$diff,0)
df3$diff <- as.numeric(df3$diff)*(-1)
View(df3)
【问题讨论】:
【参考方案1】:这是data.table
方法
library( data.table )
setDT(df3)
#get columns with timestamps
cols = grep( "^timestamp_", names(df3), value = TRUE )
#check if at least two timestampa are given, then calculate min and max
df3[ df3[, rowSums( !is.na(.SD) ), .SDcols = cols ] >= 2,
date_min := do.call( pmin, c( .SD, list( na.rm = TRUE ) ) ), .SDcols = cols ]
df3[ df3[, rowSums( !is.na(.SD) ), .SDcols = cols ] >= 2,
date_max := do.call( pmax, c( .SD, list( na.rm = TRUE ) ) ), .SDcols = cols ]
# number uniquename timestamp_1 timestamp_2
# 1: 1 student_1 2020-02-25 12:42:56 2020-02-25 12:51:22
# 2: 2 student_2 <NA> 2020-02-25 12:51:22
# 3: 3 student_3 2020-02-25 10:05:22 <NA>
# timestamp_3 timestamp_4 timestamp_5
# 1: 2020-02-25 13:00:45 2020-02-25 13:31:48 2020-02-25 14:22:57
# 2: 2020-02-25 13:00:45 2020-02-25 13:31:48 2020-02-25 15:00:00
# 3: <NA> <NA> 2020-02-25 14:05:00
# date_min date_max
# 1: 2020-02-25 12:42:56 2020-02-25 14:22:57
# 2: 2020-02-25 12:51:22 2020-02-25 15:00:00
# 3: 2020-02-25 10:05:22 2020-02-25 14:05:00
【讨论】:
已更新,每行至少检查两个不同的时间戳【参考方案2】:据我所知,您可以使用当前方法为min()
和max()
添加na.rm
参数:
df3$date_min <- apply(df3[3:7], 1, min, na.rm = TRUE)
df3$date_max <- apply(df3[3:7], 1, max, na.rm = TRUE)
df3[c("number", "uniquename", "date_min", "date_max")]
number uniquename date_min date_max
1 1 student_1 2020-02-25 12:42:56 2020-02-25 14:22:57
2 2 student_2 2020-02-25 12:51:22 2020-02-25 15:00:00
3 3 student_3 2020-02-25 10:05:22 2020-02-25 14:05:00
【讨论】:
'na.rm = TRUE ' 是缺少的选项。现在考虑所有时间戳并忽略缺失值。谢谢。以上是关于R中具有数据框的每一行的最小值和最大值的主要内容,如果未能解决你的问题,请参考以下文章
如何通过使用 dplyr 或其他包在 R 中具有最小值和最大值的查询来实现组?