r - 在 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
循环代码?任何建议,将不胜感激!
解决方案
在前面,试试这个:
# 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) { ... }
推荐阅读
- python - 转置数据框问题:为每个 df.index 和 df.column 组合在新数据框中创建一行
- java - 我的SQL命令有问题,请大家帮帮我?
- python - 在 PYOMO 中为 2 个变量定义一组特定的值
- javascript - 从 iframe CORS 获取点击数据
- javascript - 如果项目已更新,则从 v-select 更新 v-model
- excel - 简化并制作更高效的 Excel 公式
- python - 我可以展示不同的死刑方法并预测未来几年吗
- javascript - javascript递归函数在使用调试器时返回数据,但没有返回未定义
- php - 如何在 Laravel Passport 令牌中添加自定义数据?
- reactjs - redux devtools 未显示状态