r - 数据框中不同变量的嵌套for循环
问题描述
我有以下
df
P M amount date
1 1 100 03/2012
1 1 200 04/2012
1 2 100 03/2012
1 2 200 04/2012
1 3 300 03/2012
1 4 400 03/2012
...
unique(df$P)
并unique(df$M)
返回[i] 1 2 3 4 5 6 7 8 9 10
我正在尝试为每对 P 和 M 绘制数量与日期的关系(假设日期在 POXIct 中),因此我为此使用了嵌套的 for 循环。
for(i in unique(df$P)) {
for(j in unique(df$M)) {
plot(amount ~ date, subset(df, P == i & M == j),
type = "l", main = print(paste("P", i, "and M", j)))
}
}
但后来我得到了这个错误:
Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
3: In min(x) : no non-missing arguments to min; returning Inf
4: In max(x) : no non-missing arguments to max; returning -Inf
当我尝试做进一步的功能时,结果证明对于 P = 1:4,每个在 M 中出现 10 次,即每个 P = 1 有 M = 1:10
但是当我们达到 P = 5 时,它只有一对,M = 2,因此 for 循环被打破。
如何修改我的 for 循环以考虑每一对?
解决方案
2 次编辑:(1)在第二个循环中使唯一的 M 成为当前 P 的子集for
,以及(2)仅在您有足够数据的情况下绘制;我选择了“足够> 2”的数据点,但使用任何可行的方法。
for(i in unique(df$P)) {
for(j in unique(df[df$P==i, "M")) {
if(sum(df$P==i & df$M==j)>2) {
plot(amount ~ date, subset(df, P == i & M == j),
type = "l", main = print(paste("P", i, "and M", j)))
}
}
}
推荐阅读
- vert.x - 如何使用 vertx.eventBus().send() 方法将 RoutingContext 对象从路由顶点发送到其他顶点?
- python - 使用列之间的换行符读取 csv 文件
- javascript - 如何在 vue javascript 应用程序中显示服务器目录中的所有图像
- excel - 如何使用公式在 Excel 中创建地理热图
- amazon-web-services - CloudFormation 资源 AWS::S3::Bucket 未显示在 S3 控制台中
- sql - 字符串拆分函数的 SQL 分组/计数
- django - Django mixin 和 FormView 模板与 CBV 混淆
- python - 如何在 selenium 中使用 find_elements_by_tag_name 来处理浏览器上所有加载的内容?
- android - Console.log() 出现在 Web 浏览器控制台中,但在调试 ionic 应用程序时不在 Android Studio 控制台中
- sql - 查询处理日期