Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

I am having a data-frame and on that I am having these variables (Branch, Item, Sales, Stock) I need to make a for loop to extract a data: The same item which has different branches and its sales is higher than the stock and then I am saving the result in data frame. I have implemented the below code:

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] & trials$branch[i] !=  trials$branch[i+1])

{s <-data.frame( (trials$NAME[i])

  ,(trials$branch[i]))

}

1 Answer

0 votes
by (107k points)

If I were you I will not use a for loop. If you want the index of each item with more than 1 branch, then I think your data set should look something like the following:

branch item

1       1

1       1

2       2

2       1

Now in that case you can use:

# define function for amount of branches

lu <- function(x){

return(length(unique(x)))

}

# aggregate the branches

SUMM <- aggregate(branch ~ item, data = trials, FUN = unique)

# index of those with more than 1 branch

index2 <- which(lapply(SUMM$branch, FUN = lu) > 1)

# if you wanted individual index of the conditions you will be now findished

# if you want the intersection of both conditions you can finish with

allneededindex <- match(index, index2)

To extract all needed rows use:

FINISH <- trials[allneededindex, ]

If you are a beginner and want to know more about R then do check out the following R programming tutorial

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...