首页 > 解决方案 > 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]))
} 

}

标签: rfor-loopif-statement

解决方案


建议您使用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将始终对数据处理有用


推荐阅读