首页 > 解决方案 > 在 R 中使用循环创建多个图

问题描述

我的数据在这里可用,看起来像这样:

sq_id        total_forays_day age_at_loc date.x  
  <chr>            <dbl>      <dbl>      <chr>   
22897                1         41        17-06-18
22897                1         42        17-06-19
22897                2         43        17-06-20
22897                2         43        17-06-20
22897                1         44        17-06-21
22897                1         45        17-06-22

我想使用循环使plot(total_forays_day~age_at_loc)for 89 独一无二。sq_id

sq_id我可以通过运行以下命令获得独特的图:

plot(total_forays_day~age_at_loc, data=(data%>%filter(sq_id=="22641")), type="l")

但这不是一种有效的方法,因为我需要可视化 89 个图。

我试过了:

par(mfrow=c(10,10))
for(i in 1:1) { #loop over loop.vector
    plot(total_forays_day~age_at_loc[,i], data=data)
}

这不起作用。我收到以下错误消息:

age_at_loc[, i] 中的错误:维数不正确

我应该如何修复我的for循环代码?任何建议,将不胜感激!

标签: rloopsplotsubset

解决方案


在前面,试试这个:

# remove [1:3] when you are comfortable with this and want to see all of them
for (d in split(data, data$sq_id)[1:3]) {
  plot(total_forays_day ~ age_at_loc, data=d)
  readline("next") # or locator(1)
}

您遇到的问题:

  • total_forays_day~age_at_loc[,i]像一个框架一样对待age_at_loc,但它是一个向量
  • total_forays_day~age_at_loc[i](正如我错误地建议的那样)正在将向量与单个数字进行比较,这不起作用,因为plot期望所有向量的长度相同(age_at_loc[i]长度为 1)

您的问题是您没有以有效的方式拆分数据。如果您查看来自 的结果split(...),您会看到类似

str(split(data, data$sq_id)[1:3])
# List of 3
#  $ 22640:'data.frame':    102 obs. of  4 variables:
#   ..$ sq_id           : int [1:102] 22640 22640 22640 22640 22640 22640 22640 22640 22640 22640 ...
#   ..$ total_forays_day: int [1:102] 1 1 1 1 1 1 1 1 1 1 ...
#   ..$ age_at_loc      : int [1:102] 49 49 51 51 52 52 53 53 54 54 ...
#   ..$ date.x          : Factor w/ 124 levels "17-06-07","17-06-08",..: 2 2 3 3 4 4 5 5 6 6 ...
#  $ 22641:'data.frame':    52 obs. of  4 variables:
#   ..$ sq_id           : int [1:52] 22641 22641 22641 22641 22641 22641 22641 22641 22641 22641 ...
#   ..$ total_forays_day: int [1:52] 1 1 1 1 1 1 1 1 2 2 ...
#   ..$ age_at_loc      : int [1:52] 49 51 52 53 54 55 59 60 61 61 ...
#   ..$ date.x          : Factor w/ 124 levels "17-06-07","17-06-08",..: 2 3 4 5 6 7 8 9 10 10 ...
#  $ 22653:'data.frame':    35 obs. of  4 variables:
#   ..$ sq_id           : int [1:35] 22653 22653 22653 22653 22653 22653 22653 22653 22653 22653 ...
#   ..$ total_forays_day: int [1:35] 2 2 2 2 1 2 2 1 2 2 ...
#   ..$ age_at_loc      : int [1:35] 58 58 59 59 60 61 61 62 63 63 ...
#   ..$ date.x          : Factor w/ 124 levels "17-06-07","17-06-08",..: 10 10 11 11 12 13 13 14 15 15 ...

注意列表中的每个元素sq_id在其框架中是如何相同的。一个有 102 行的框架也是如此split(...)[[1]],它们sq_id都是"22640". 通过用 迭代它for (d in split(data, data$id)),循环中的每个通道都d分配了这些sq_id单帧之一。

readlines("next")vs的使用locator(1)纯粹是主观和用户体验。如果您更喜欢按回车,请选择第一个;如果您喜欢单击图像,请选择第二个。

知道如果您正在使用拆分数据做其他事情,那么拆分一次并使用多次可能会有所帮助,ala

splitdata <- split(data, data$sq_id)
for (d in splitdata) { ... }

推荐阅读