Reputation:
I Have data set with these variables (Branch, Item, Sales, Stock) I need to make a for loop to extract a data with the following
The same item which has
1-different branches
2- its sales is higher than the stock
and save the result in data frame The code I used is
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]))
}
}
Upvotes: 2
Views: 85
Reputation: 329
As you just want to fix your code:
You missed to set one =
in your code.
Use:
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()
}
Upvotes: 1
Reputation: 41
Suggest you use dplyr library, post installing considering "df" is your dataset, use the below commands for question 1 and 2
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"]
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 > question_two$Stock),"Item"]
Couldn't help but solve without dplyr, however suggest, if not used yet, dplyr will always be useful for data crunching
Upvotes: 1