r - For循环提取数据
问题描述
我有这些变量的数据集(分支、项目、销售、库存)我需要创建一个 for 循环来提取具有以下内容的数据
同一商品有
1-不同的分店
2-其销售额高于库存
并将结果保存在数据框中我使用的代码是
trials <- sample_n(Data_with_stock,1000)
for (i in 1:nrow(trials))
{
if(trials$sales[i] > trials$stock[i] & trials$item[i] == trials$item[i+1] & trials$branch[i] != trials$branch[i+1])
{s <-data.frame( (trials$NAME[i])
,(trials$branch[i]))
}
}
解决方案
建议您使用dplyr库,安装后考虑“df”是您的数据集,对问题 1 和 2 使用以下命令
问题 1
question_one =df %>%
group_by(Item) %>%
summarise(No_of_branches = n_distinct(Branch))
items_with_more_than_one_branch =question_one[which(question_one$No_of_branches>1)"Item"]
问题2:同样,
问题二=df %>%
group_by(Item) %>%
summarise(Stock_Val = sum(Stock), Sales_Val = sum(Sales))
item_with_sales_greater_than_stock = question_two[which(question_two$Sales > question_two$Stock),"Item"]
没有dplyr 无法解决,但是建议,如果尚未使用,dplyr将始终对数据处理有用
推荐阅读
- ios - 没有在窗口上调用 traitCollectionDidChange
- python - 如何在python中将多列表转换为字典
- c++ - Windows 上的英特尔 C++ 编译器灾难性错误:无法打开源文件“bits/unique_ptr.h”
- sql - 如何选择具有相同列条件的多行
- python - 加快从 Golang 的 exec packaqe 访问 python 程序
- python - Pandas:在 Pandas 数据框中查找连续索引的起始值
- javascript - 如何以正确和高效的方式避免在 React 中改变本地状态
- python - GCP:无法连接到云 TPU
- javascript - 第二次尝试反应功能松散状态
- swift - 快速省略命名空间