r 提取行之间的分钟并将它们相加

问题描述 投票:0回答:2

我有以下数据集:

structure(list(Zeit = c("11:35:00 AM", "12:43:00 PM", "12:48:00 PM", 
"12:53:00 PM", "12:58:00 PM", "1:03:00 PM", "1:08:00 PM", "1:13:00 PM", 
"1:18:00 PM", "1:23:00 PM", "1:28:00 PM", "1:33:00 PM", "1:38:00 PM", 
"1:43:00 PM", "1:48:00 PM"), SRB.konz = c("0", "0", "0", "0", 
"0", "0", "0", "0,0546352106", "1,89348740676", "14,16501124644", 
"33,21026613524", "45,19095110716", "51,16722074468", "46,13852290212", 
"38,99889779356")), row.names = c(NA, 15L), class = "data.frame")

我想创建一个新列,其中包含经过的时间(以分钟为单位)。

由于某种原因,我遇到了时间 (Zeit) 列的问题。

r time time-series
2个回答
0
投票

通常需要将日期转换为日期时间对象,例如

POSIXct()
。因此,在前面添加今天的日期,创建日期时间,然后使用
format()
提取分钟。

paste(Sys.Date(), dat$Zeit) |>
    as.POSIXct() |>
    format("%M") |>
    as.integer()

#  [1] 35 43 48 53 58  3  8 13 18 23 28 33 38 43 48

0
投票

这是获取每次观察所用时间的解决方案。在本例中,我将起点用作您的

Zeit
列的第一次。

library(dplyr)
library(lubridate)

df |>
  # Convert string to POSIXct date-time object, using AM and PM
  mutate(across(Zeit, ~parse_date_time(.x, "%H:%M:%S %p"))) |>
  # Get minimum time to use it as the starting point
  mutate(mintime = min(Zeit)) |>
  # Calculate interval in minutes from the mintime to each Zeit
  mutate(mins = as.numeric(interval(mintime,Zeit),"minutes"))

#                  Zeit       SRB.konz             mintime mins
#1  0000-01-01 11:35:00              0 0000-01-01 11:35:00    0
#2  0000-01-01 12:43:00              0 0000-01-01 11:35:00   68
#3  0000-01-01 12:48:00              0 0000-01-01 11:35:00   73
#4  0000-01-01 12:53:00              0 0000-01-01 11:35:00   78
#5  0000-01-01 12:58:00              0 0000-01-01 11:35:00   83
#6  0000-01-01 13:03:00              0 0000-01-01 11:35:00   88
#7  0000-01-01 13:08:00              0 0000-01-01 11:35:00   93
#8  0000-01-01 13:13:00   0,0546352106 0000-01-01 11:35:00   98
#9  0000-01-01 13:18:00  1,89348740676 0000-01-01 11:35:00  103
#10 0000-01-01 13:23:00 14,16501124644 0000-01-01 11:35:00  108
#11 0000-01-01 13:28:00 33,21026613524 0000-01-01 11:35:00  113
#12 0000-01-01 13:33:00 45,19095110716 0000-01-01 11:35:00  118
#13 0000-01-01 13:38:00 51,16722074468 0000-01-01 11:35:00  123
#14 0000-01-01 13:43:00 46,13852290212 0000-01-01 11:35:00  128
#15 0000-01-01 13:48:00 38,99889779356 0000-01-01 11:35:00  133
© www.soinside.com 2019 - 2024. All rights reserved.