我的数据集将样本作为行,将变量作为cols (X1-X3)。每个样品是10倍(1-10)的8个位点(a-h)之一的组合。
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个数据点。请看下面的例子(请只参考栗色的数据)。

(Lamothe et al.,2019)
发布于 2020-02-23 08:57:52
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)

https://stackoverflow.com/questions/60357506
复制相似问题