gpt4 book ai didi

r - 在 R 中按指定的时间长度扩展时间序列

转载 作者:行者123 更新时间:2023-12-04 04:49:01 25 4
gpt4 key购买 nike

我想根据 POSIXct 格式的日期时间列扩展 R 中的数据框。我的数据框中的每一行日期时间(列 [1])当前代表一个时间块的开始。时间块的长度以秒为单位在列 [2] 中给出。我想扩展数据框,为该时间块中的每一秒提供一个单独的时间戳(行),如第 2 列中所指定。

以下是一些示例数据:

structure(list(datetime = structure(1:5, .Label = c("14/04/2013 17:42:29", 
"14/04/2013 17:43:49", "14/04/2013 17:43:58", "14/04/2013 17:44:03",
"14/04/2013 17:44:11"), class = "factor"), duration = c(1L, 5L,
2L, 3L, 2L), mean = c(1.17, 2.36, 1.05, 1.43, 1.47)), .Names = c("datetime",
"duration", "mean"), class = "data.frame", row.names = c(NA,
-5L))

这是我目前拥有的:
             datetime duration mean
14/04/2013 17:42:29 1 1.17
14/04/2013 17:43:49 5 2.36
14/04/2013 17:43:58 2 1.05
14/04/2013 17:44:03 3 1.43
14/04/2013 17:44:11 2 1.47

这就是我想要的结果:
             datetime duration mean
14/04/2013 17:42:29 1 1.17
14/04/2013 17:43:49 1 2.36
14/04/2013 17:43:50 1 2.36
14/04/2013 17:43:51 1 2.36
14/04/2013 17:43:52 1 2.36
14/04/2013 17:43:53 1 2.36
14/04/2013 17:43:58 1 1.05
15/04/2013 17:43:59 1 1.05
14/04/2013 17:44:03 1 1.43
14/04/2013 17:44:04 1 1.43
14/04/2013 17:44:05 1 1.43
14/04/2013 17:44:11 1 1.47
14/04/2013 17:44:12 1 1.47

我无法找到执行此处理任务的简单方法,并且对类似问题的回答并没有为我提供此问题的解决方案(即 How to convert 10-minute time blocks to 1-minute intervals in RExpand Categorical Column in a Time Series to Mulitple Per Second Count Columns )。我认为它的功能类似于 split() , merge() , 和 ddply()可能会有所帮助,但我无法解决。我仍在学习,所以任何建议将不胜感激。

最佳答案

您可以使用 lapply创建一个 data.frame对于每个段然后 rbind最后把所有的结果放在一起,就像这样......

res <- lapply( 1:nrow(df) , function(x){ data.frame(
datetime = strptime( df[ x , 1 ] , format = "%d/%m/%Y %H:%M:%S" ) + ( seq_len( df[ x , 2 ] ) - 1 ) ,
duration = rep( 1 , df[ x , 2 ] ) ,
mean = rep( df[ x , 3 ] , df[ x , 2 ] ) ) } )

do.call( rbind , res )
# datetime duration mean
#1 2013-04-14 17:42:29 1 1.17
#2 2013-04-14 17:43:49 1 2.36
#3 2013-04-14 17:43:50 1 2.36
#4 2013-04-14 17:43:51 1 2.36
#5 2013-04-14 17:43:52 1 2.36
#6 2013-04-14 17:43:53 1 2.36
#7 2013-04-14 17:43:58 1 1.05
#8 2013-04-14 17:43:59 1 1.05
#9 2013-04-14 17:44:03 1 1.43
#10 2013-04-14 17:44:04 1 1.43
#11 2013-04-14 17:44:05 1 1.43
#12 2013-04-14 17:44:11 1 1.47
#13 2013-04-14 17:44:12 1 1.47

关于r - 在 R 中按指定的时间长度扩展时间序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17721389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com