0

I have a data frame having these columns

Qty  Sales Price  COGS  
  1          500   200  
  2          900   400   
  3         1000   300   
  1          300   150

I want to calculate the profit for every row. So for row 1 if Sales Price - COGS (500-200) profit is 300. one condition is that if qty is more than 1 then QtySales Prce- QtyCOGS= gross profit.

I used loop

for (i in 1:nrow(Data)) {
  if(Data[i,"Qty"]<=1) {Data[i,"Margin"]<-Data[i,"Sales.Price"]-Data[i,"COGS"]}    
  if(Data[i,"Qty"]>=1){Data[i,"Margin"]<-Data[i,"Qty" * "Sales.Price"]-Data[i,"Qty * "COGS"]}
}

But

I want to use apply function

and return my answer in data frame as Margin appended as an vector in my current data frame and not as list or matrix.

Qty    Sales Price    COGS    Margin  
  1            500     200       300  
  2            900     400      1000  
  3           1000     300      2100  
  1            300     150       150  
1
  • 1
    Please read ?Arithmetic and then ?S4groupGeneric, many of the functions in R are vectorized (not only on vectors but on matrices and even data frames). Writing unnecessary loops in apply instead of a for won't get you far. Commented Jan 17, 2016 at 7:37

1 Answer 1

2

There is no need for an apply function. You can just use a vectorized approach:

Data$Margin <- Data$Qty * (Data$Sales.Price - Data$COGS)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for such a simple answer:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.