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
?Arithmeticand then?S4groupGeneric, many of the functions in R are vectorized (not only on vectors but on matrices and even data frames). Writing unnecessary loops inapplyinstead of aforwon't get you far.