I have a very long function whose arguments take in different threshold values for different variables and give an event study result at the end. I want to compute this function over different list of values.
V1 4 4 0.05 2 0.8
V2 5 4 0.05 2 0.8
V1 and V2 are two different combinations of my function's arguments. Each column represent an argument of my function. How can I iterate through each row given each column is a different argument of the function?
CodePudding user response:
Something like this perhaps assuming your columns are a, b, c, d, e and dataset is df. Would be better if you provided some data. Gives you a named list of results using V1, V2, etc as the name.
results <- list()
for (V in 1:nrow(df)){
results[[df$a[V]]] <- myfunction(arg1 = df$b[V], arg2 = df$c[V],
arg3 = df$d[V], arg4 = df$e[V])
}
CodePudding user response:
Here's an example using purrr::pmap. It captures the results as a column in the same dataframe that holds the data.
library(dplyr)
library(purrr)
#sample data set
data <- data.frame(
a = c(1, 2, 3),
b = c(7, 8, 9),
c = c(4, 5, 6))
rownames(data) <- c("V1", "V2", "V3")
data %>%
mutate(results = pmap_dfr(., function(a, b, c) {data.frame(results = a b c)} ))
# a b c results
#V1 1 7 4 12
#V2 2 8 5 15
#V3 3 9 6 18