I have a dataframe with multiple numeric and character columns. For example,
> df <- data.frame(Name=c('John','Tom','Sarah'), Quantity=c(3,4,5), Price=c(5,6,7))
> df
Name Quantity Price
1 John 3 5
2 Tom 4 6
3 Sarah 5 7
I would like to write a function that checks whether name is John or Tom and calculates, say, Sales=Quantity*Price. This function would look like the following:
myFunc <- function(x) {
if (Name %in% c('John','Tom') {
Sales <- Quantity * Price
}
}
I would like to send each row of my dataframe to the function to get the following output:
Name Quantity Price Sales
1 John 3 5 15
2 Tom 4 6 24
3 Sarah 5 7 NA
I tried following the suggestions in the link below without any success: Call apply-like function on each row of dataframe with multiple arguments from each row
How can I achieve this in R? Thanks for any help.