我的数据集的样本作为行,变量作为cols(X1-X3)。每个样本都是八个位置(a-h)之一在10倍(1-10)时的组合。
df = data.frame(site = c(rep ("a", 10), rep("b",10),rep("c",10),
rep("d",10),rep("e",10), rep("f",10),
rep("g",10),rep("h", 10)),
time = rep(1:10,8),
matrix(rnorm(80*3), nrow=80))
我使用dist
函数为我的样本计算了一个欧几里得距离矩阵,因此计算出每对样本之间的距离,对角线是每个样本与自身之间的距离(= 0)。
mx = as.matrix (df)
rownames (mx) = paste(df$site, df$time)
mx = subset (mx, select = -c(site, time))
dist.mx = as.matrix (dist(mx, method = "euclidean"))
对于每个站点,我想根据其滞后时间绘制后续样本之间的距离。例如在第一个滞后中有9个距离值(即1-2、2-3、3-4年的距离...),在滞后2中将有8个距离(即1-3、2年之间) -4、3-5、4-6 ...),滞后3-7距离(即1-4、2-5、3-6、4-7 ...每个站点总共45个数据点。请参见下面的示例(请仅参考栗色数据)。
library(tidyverse)
# Convert to longer data frame
dist.mx %>%
as.data.frame() %>%
rownames_to_column("col1") %>%
pivot_longer(-col1, names_to = "col2", values_to = "dist") %>%
# extract site and time from each sample
separate(col1, c("site1", "time1"), convert = T) %>%
separate(col2, c("site2", "time2"), convert = T) %>%
# compare lags within sites
filter(site1 == site2, time1 < time2) %>%
mutate(lag = time2 - time1) %>%
ggplot(aes(lag, dist)) +
geom_point() +
geom_smooth(method = "lm", se = F) +
scale_x_continuous(breaks = 1:10, minor_breaks = NULL) +
facet_wrap(~site1)