【问题标题】:For loop to extract dataFor循环提取数据
【发布时间】:2020-04-19 13:36:02
【问题描述】:

我有这些变量的数据集(分支、项目、销售、库存)我需要创建一个 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]))
} 

}

【问题讨论】:

  • 如果一个项目有不同的分支,变量分支会是什么样子?
  • 即使有两个== 这个trials$item[i] = trials$item[i] 也没有多大意义。
  • 因为不同的分店在不同的地区销售相同的商品
  • 没有人我需要进行 for 循环,因为我需要将所有答案都放在一个数据框中,for 循环应该比较行中的项目以及分支和内部以有 if 条件来比较销售和库存,我需要修复我的代码

标签: r for-loop if-statement


【解决方案1】:

建议您使用 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&gt;1)"Item"]

问题2:同样,

question_two = 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 &gt; question_two$Stock),"Item"]

没有 dplyr 无法解决,但是建议,如果尚未使用,dplyr 将始终对数据处理有用

【讨论】:

  • 它不起作用 – Sepa Mostafa 16 小时前看假设我们有 20 家药店分店假设他们销售 100 件商品我需要查找商品销售额是否大于库存,以便其他分支机构可以支持这件商品 – Sepa Mostafa 16 小时前 所以这 100 件商品在他们有库存和销售单位的所有药店都是一样的之前你能帮我找到这个选择中的项目吗
【解决方案2】:

因为你只是想修复你的代码:

您错过了在您的代码中设置一个=

用途:

trials <- sample_n(Data_with_stock,1000)
# next you need first to define s used in your loop
s <- array(NA, dim = c(1,2)) # as you only save 2 things in s per iteration

for (i in  1:nrow(trials)) {
# but I dont get why you compare the second condition.

if(trials$sales[i] >  trials$stock[i] & trials$item[i] ==  trials$item[i] & trials$branch[i] !=  trials$branch[i+1]) {

s[i,] <- cbind(trials$NAME[i], trials$branch[i])
} else {
s[i,] <- NA # just to have no problem with the index i, you can delete the one with na afterwards with na.omit()
}

【讨论】:

  • 看看假设我们有 20 家药店分店假设他们销售 100 件商品我需要查找商品销售额是否大于库存,以便其他分支机构可以支持该商品
  • 所以这 100 件商品在他们有库存和销售单位的所有药店都是一样的
  • 你能帮我找到这个选择中的项目吗
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-11
  • 2017-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
相关资源
最近更新 更多