【发布时间】:2019-10-07 21:24:34
【问题描述】:
我有一个数据框,其中包含日期时间、ID、时间和深度的列。我正在使用 ddply 来获取每个唯一日期时间的平均时间和深度,因为有重复的日期时间行。但是,在每个日期时间块中,可能有多个唯一的“id”值,并且对于单个 id 再次重复行。因此,我需要为每个 datetime 块做的实际上是计算从 id 块中获取的所有唯一时间的平均值。即我首先需要从每个 id 块中获取唯一时间值,然后我想计算使用此方法为每个 datetime 块返回的所有唯一时间值的平均值。我正在尝试使用 %>% 来执行此操作,但这对我来说是新语法,我正在苦苦挣扎。 ddply 包装器中针对日期时间的任何帮助或替代建议将不胜感激。我在下面提供一个示例。
> dput(df3)
structure(list(datetime = c("23/03/2017 14:13:45", "23/03/2017 14:13:45",
"23/03/2017 14:13:45", "23/03/2017 14:13:45", "23/03/2017 14:13:45",
"23/03/2017 14:13:45", "23/03/2017 14:13:45", "23/03/2017 14:13:45",
"23/03/2017 14:13:45", "23/03/2017 14:13:45", "23/03/2017 14:15:15",
"23/03/2017 14:15:15", "23/03/2017 14:15:15", "23/03/2017 14:15:15",
"23/03/2017 14:15:45", "23/03/2017 14:15:45", "23/03/2017 14:16:15",
"23/03/2017 14:16:15", "23/03/2017 14:16:15", "23/03/2017 14:16:15",
"23/03/2017 14:16:15", "23/03/2017 14:16:15", "23/03/2017 14:16:15"
), id = c(11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 12L,
12L, 12L, 13L, 14L, 14L, 15L, 16L, 16L, 16L, 17L, 18L, 18L),
time = c(10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
3L, 3L, 3L, 1L, 2L, 2L, 1L, 3L, 3L, 3L, 1L, 2L, 2L), dep = c(0.448675132,
0.448675132, 0.448675132, 0.448675132, 0.448675132, 0.448675132,
0.448675132, 0.448675132, 0.448675132, 0.448675132, 0.285520539,
0.285520539, 0.285520539, 0.285520539, 0.316112025, 0.316112025,
0.326309187, 0.356900674, 0.356900674, 0.356900674, 0.38749216,
0.326309187, 0.326309187)), class = "data.frame", row.names = c(NA,
-23L))
我的尝试不起作用:
#convert datetime to POSIXct
df3$datetime = as.POSIXct(strptime(df3$datetime, format="%d/%m/%Y %H:%M:%S"), tz="UTC")
#Now condense the dateframe by unique datetime summarising tim and dep cols
dfCondensed = ddply(df3, .(datetime), summarise,
#get the mean time for each unique datetime, but calculate this using
#all the unique time values found within each unique id
meantime = group_by(id) %>% unique(time) %>% mean(),
#do the same as above but for dep
meandep = group_by(id) %>% unique(dep) %>% mean())
期望的输出
> dfCondensed
datetime tim dep
1 23/03/2017 14:13:45 10.00 0.4486751
2 23/03/2017 14:15:15 2.00 0.2855205
3 23/03/2017 14:15:45 2.00 0.3161120
4 23/03/2017 14:16:15 1.75 0.3492528
【问题讨论】: