I have a user-defined function that I would like to use across all rows in a dataframe. I've tried using the apply() function to accomplish this but I do not think my syntax is correct. I've also tried to make another user-defined function to accomplish this, but it been creating errors. I tried to make a minimal reproducible example of the error but it does not seem to have the same problem as my actual code. However, in the minimal reproducible example, I did notice that the class of the variables in the "result" dataframe are all character and I would expect some of them to be doubles. I'm hoping that at least correcting this issue in the example code will help me to figure out the problem in the actual code.
Any advice on a good way to do this would be appreciated.
library(tidyverse)
function1 <- function(cut, depth, price){
result <- data.frame(cut = character(),
depth = double(),
price = double(),
new_value = double(),
new_char = character())
new_value <- depth*price
new_char <- paste0(cut, "kjh", as.character(depth))
result[nrow(result) + 1,] <- c(cut, depth, price, new_value, new_char)
print(result)
}
#use function with variables
function1("good", 100, 3)
#use function on all rows in a dataframe
df <- head(diamonds)
function2 <- function(){
for(i in 1:nrow(df)) {
row <- df[i,]
#function1 on each row
function1(row$cut, row$depth, row$price)
}
}
function2()
#how to use apply function?
apply(df, 1, function1(cut, depth, price))