对于数据框中的每个时间点,我都有 2 到 4 个测量值。我想计算移动平均值,这样对于给定的时间点,我有一个值,即该时间点的所有测量值的平均值+之前的时间点和之后的时间点。
cellcounts <-c(80, 188, 206, 162, 106, 90, 85, 109, 87, 94, 86, 196, 132, 135, 84, 122, 67, 88, 81, 121, 9, 93, 117, 91, 108, 103, 119, 100, 18, 98, 93, 119, 140, 160, 101, 82, 111, 103, 28, 72, 144, 85, 1)
time <-c(-2.7, -2.8, -2.9, -3.0, -3.1, -3.2, -3.3, -3.4, -3.5, -3.6, -2.7, -2.8, -2.9, -3.0, -3.1, -3.2, -3.3, -3.4, -3.5, -3.6, -3.9, -3.0, -3.1, -3.2, -3.3, -3.4, -3.5, -3.7, -2.5, -2.6, -2.9, -3.0, -3.2, -3.3, -3.4, -3.5, -3.7, -3.8, -2.5, -2.6, -3.7, -3.8, -3.9)
df <- data.frame(cellcounts, time)
df <- df[order(df$time),]
df
zoo::rollapply(df, width = 3, FUN = mean, align = "center", fill = NA)
有这样的事吗?
x <- with(df, tapply(cellcounts, time, mean)) |>
zoo::rollapply(width = 3, FUN = mean, align = "center", fill = NA)
## make a data.frame from the result above
df1 <- data.frame(time = as.numeric(names(x)), cellmeans = x)
df1
#> time cellmeans
#> -3.9 -3.9 NA
#> -3.8 -3.8 72.44444
#> -3.7 -3.7 106.61111
#> -3.6 -3.6 106.02778
#> -3.5 -3.5 100.00000
#> -3.4 -3.4 99.16667
#> -3.3 -3.3 105.33333
#> -3.2 -3.2 106.02778
#> -3.1 -3.1 113.44444
#> -3 -3.0 124.41667
#> -2.9 -2.9 154.30556
#> -2.8 -2.8 139.55556
#> -2.7 -2.7 120.00000
#> -2.6 -2.6 63.66667
#> -2.5 -2.5 NA
# another way of creating a results df
df2 <- x |> as.data.frame()
df2$time <- x |> names() |> as.numeric()
df2
#> x time
#> -3.9 NA -3.9
#> -3.8 72.44444 -3.8
#> -3.7 106.61111 -3.7
#> -3.6 106.02778 -3.6
#> -3.5 100.00000 -3.5
#> -3.4 99.16667 -3.4
#> -3.3 105.33333 -3.3
#> -3.2 106.02778 -3.2
#> -3.1 113.44444 -3.1
#> -3 124.41667 -3.0
#> -2.9 154.30556 -2.9
#> -2.8 139.55556 -2.8
#> -2.7 120.00000 -2.7
#> -2.6 63.66667 -2.6
#> -2.5 NA -2.5
创建于 2023-09-20,使用 reprex v2.0.2