类似动物园里pandas的滚动均值函数

Rolling mean function similar to pandas in zoo

我想创建一些地球化学数据的滚动平均值。目前,我有从 0 毫米到 45.7 毫米每 1 毫米的数据,我想对每 10 毫米进行平均以创建 1 厘米的平均值。

这是目前的数据,但它仍然没有给我 1 厘米的平均值。有人能告诉我哪里出错了吗?谢谢


wapPbTa<-read.csv("wappbta.csv",header=TRUE)

wapPbTa<-wapPbTa[-c(251:458), ] 

library(ggplot2)
library(tidypaleo)
library(zoo)
width <- 10

RM<-rollmean(x = wapPbTa$PbTa, k = width,fill=NA)

##Averaged data

ggplot(wapPbTa, aes(x =RM , y = Depth))+
  labs(y = "Depth (cm)")+
  geom_lineh(size=1)+
  geom_point(size=2)+
  theme_classic()+
  scale_y_reverse()

## Unaveraged data
ggplot(wapPbTa, aes(x =PbTa , y = Depth))+
  labs(y = "Depth (cm)")+
  geom_lineh(size=1)+
  geom_point(size=2)+
  theme_classic()+
  scale_y_reverse()

structure(list(Depth = c(0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 
0.8, 0.9, 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9), PbTa = c(0.163857678, 
0.161569533, 0.086305592, 0, 0.006086142, 0, 0, 0.044096031, 
0.050739958, 0.088385995, 0.104100946, 0.133012821, 0, 0.127524872, 
0.046368715, 0.02514558, 0.109383676, 0.081979695, 0.0766503, 
0.064679583)), row.names = c(NA, 20L), class = "data.frame")

此类问题通常与重塑数据有关。格式应该是长格式,数据是宽格式。请参阅 this post 了解如何将数据从宽格式重塑为长格式。

library(ggplot2)
library(dplyr)
library(tidyr)
library(tidypaleo)
library(zoo)

width <- 10
wapPbTa$RM <- rollmeanr(x = wapPbTa$PbTa, k = width, fill = NA)

wapPbTa %>%
  pivot_longer(cols = -Depth) %>%
  ggplot(aes(x = value, y = Depth, colour = name)) +
  geom_lineh(size = 1) +
  geom_point(size = 2) +
  scale_y_reverse() +
  scale_colour_manual(
    breaks = c("PbTa", "RM"),
    values = c("black", "blue")
  ) +
  labs(y = "Depth (cm)") +
  theme_classic()