在该数据 table 中发生了 x 个事件之后,您将如何消除一系列事件?

How would you eliminate a sequence of events after x events had occured in this data table?

我有一个 data.frame,它给出了不同模拟中每个 x 和 y 坐标的事件发生时间。我在下面使用 dput().

附上了这个 table 的头部
head_data<-structure(list(x = c(987.353265152362, 570.817987386894, 1147.5681499552, 
637.526076016409, 1439.13510253106, 1396.6452808061), y = c(1802.08232812874, 
349.336242713164, 1789.49467712533, 361.611973188148, 1492.44148360367, 
1459.91771610835), id = 1:6, `simulation 1` = c(1100, 600, 1200, 
400, 900, 1000), `simulation 2` = c(1500, 1400, 1600, 1200, 1200, 
1300), `simulation 3` = c(1200, 1100, 1200, 1000, 900, 900), 
    `simulation 4` = c(1300, 800, 1200, 900, 1100, 1100), `simulation 5` = c(1500, 
    1200, 1400, 1100, 1300, 1200), `simulation 6` = c(200, 1400, 
    100, 1100, 600, 600)), row.names = c(NA, 6L), class = "data.frame")

首先将数据熔化成长格式

data_long <- melt(head_data, id.vars = c('x', 'y', 'id'), value.name = 'time', variable.name = 'sim')

然后我对事件的时间进行排序

times <- sort(unique(data_long$time))

现在我通过对每个 sim 在每个时间间隔的事件求和,将这个 data.frame 事件转化为总流行率。

data_clust_10 <- data_long %>% group_by(sim) %>%
  do(data.frame(time=times, infected=sapply(times, function(x) sum(.$time <= x))))

然后我通过删除阈值后的所有事件来过滤流行数据,完整数据中有 1000 个 x 和 y 坐标,但我们每个 sim 只处理 6 个个体,所以假设 2 个事件.

data_clust_10_cut<-filter(data_clust_10, infected < 2)

是否可以将此数据帧转换回 head_data 的原始格式?我可以使用 dcast() 吗?我认为行数会有所不同,所以它不起作用或者我错了吗?我想这样做是因为我将使用精化后的数据来估计方差系数。仔细想想其实我觉得把原来的table、head_data中的时间安排一下,然后剔除超过我的流行度阈值的事件数可能是最好的解决办法,但我会有兴趣了解是否可以在这种情况下使用 dcast()。我想让原来 table 中的事件顺序按照事件发生的时间排序,然后我想消除所有事件发生后发生的所有事件,不管时间是多少。

这是您要找的吗:

library(tidyr)
data_clust_10_cut %>% pivot_wider(names_from="sim", values_from="infected")
# # A tibble: 8 x 7
#     time `simulation 1` `simulation 2` `simulation 3` `simulation 4`
#    <dbl>          <int>          <int>          <int>          <int>
# 1   100              0              0              0              0
# 2   200              0              0              0              0
# 3   400              1              0              0              0
# 4   600             NA              0              0              0
# 5   800             NA              0              0              1
# 6   900             NA              0             NA             NA
# 7  1000             NA              0             NA             NA
# 8  1100             NA              0             NA             NA
# # … with 2 more variables: `simulation 5` <int>, `simulation 6` <int>
#