Reputation: 31
Need to convert a for loop to lapply to reduce computational work, however failed to adjust all i labels in the lapply since it is a long process
sample:
for (i in 1:76){
tryCatch({
model <- nplr(x = splitlist[[i]]$dose, y = splitlist[[i]]$IC, npars = "all")
.... computation of some variables, then
vdata = data.frame(splitlist[[i]]$dose, splitlist[[i]]$viability, splitlist[[i]]$IC)
further computation of variables assingned to i
then:
path = paste0(dir_path,"/results/Patient/",input$txt,"/combined_plots/",titleframe[i, ],".png", sep ="")
}
...etc
Upvotes: 1
Views: 289
Reputation: 2368
You could try to write a function that does your operation, then lapply
said function.
EX
complicated_function <- function(df){
tryCatch({
model <- nplr(x = df$dose, y = df$IC, npars = "all")
---stuff ----
out <- stuff
}
Then you could do:
outobject <- lapply(your_data, FUN = complicated_function)
I don't know if that puts on you on the right track. If you have some representative data I could help more, but that methodology probably will work for you.
Here is an even more complete example
# Generate Some Fake Data
library(tidyverse)
create_random_dfs <- function(x){
cats <- sample(LETTERS, size = 10, replace = TRUE)
x1 <- rnorm(10, 0, 1)
x2 <- rnorm(10, 0, 1)
y <- 3*x1 + 1*x2
tibble(cats, x1, x2, y)
}
df <- lapply(1:100, create_random_dfs)
# Custom Function that works for one dataframe
df[[1]]
my_function <- function(input){
fit <- lm(y ~ x1 + x2, data = input)
broom::tidy(fit)
}
lapply(df, my_function)
Upvotes: 1