首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >绘制连续样本的距离作为其在R中的时间延迟的函数

绘制连续样本的距离作为其在R中的时间延迟的函数
EN

Stack Overflow用户
提问于 2020-02-23 06:36:34
回答 1查看 130关注 0票数 1

我的数据集将样本作为行,将变量作为cols (X1-X3)。每个样品是10倍(1-10)的8个位点(a-h)之一的组合。

代码语言:javascript
复制
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)。

代码语言:javascript
复制
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)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-23 08:57:52

代码语言:javascript
复制
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)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60357506

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档