【问题标题】:Plotting distances of consecutive samples as a function of their time lag in R绘制连续样本的距离作为它们在 R 中的时间滞后的函数
【发布时间】:2020-02-22 22:36:33
【问题描述】:

我的数据集有样本作为行和变量作为 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 个数据点。见下面的例子(请只参考栗色的数据)。

(拉莫特等人,2019 年)

【问题讨论】:

  • 你能分享一个示例数据集以便我们研究它吗?如果你这样做会更容易帮助你。
  • 谢谢。我添加了虚拟数据。

标签: r ggplot2 subset distance


【解决方案1】:
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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-02
    • 2020-04-03
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 2021-08-18
    相关资源
    最近更新 更多