How to dynamically name files in lapply?

Viewed 123

Here's some sample code:

dat <- data.frame(test1=runif(100,0,1),
                  test2=runif(100,0,1),
                  test3=runif(100,0,1))

variable_of_interest <- "test1"

dat_multi <- 3


test_save <- function(dat, x_seq) {
  saveRDS(dat, file=paste0("data/", variable_of_interest,"_", x_seq,".RDS"))
}



test_func <- function(dat, dat_multi,x) {
  res <- as.data.frame(as.matrix(dat*dat_multi))
  
  dat_test <- rbind(melt(res$test1) %>% mutate(Var = "First_Testing_1"),
                    melt(res$test2) %>% mutate(Var = "Different_Testing_2"),
                    melt(res$test3) %>% mutate(Var = "Very_Different_Testing_3"))
  
  test_save(dat_test,x)
}

x_seq <- 1:3

lapply(x_seq, function(x) test_func(dat, dat_multi, x))

Just looking to save files with the variable_of_interest and the iteration in the filename:

data/test1_1.RDS
data/test1_2.RDS
data/test1_3.RDS
1 Answers

The loop can be

lapply(x_seq, function(x) test_save(dat, x))

It is better to use a different lambda name than the object name already created in the global env. Also, if 'dat' is the same, then the lambda function can have a single argument


In the updated function, there are some issues in the code i.e. $ is used for extraction on a matrix object. Instead, it would be [ . It can be made compact with

test_func <- function(dat, dat_multi, x) {
  res <- as.matrix(dat*dat_multi)
  names(res) <- paste0("Testing_", seq_len(ncol(res)))
  test_save(melt(res), x)
 
}
lapply(x_seq, function(x) test_func(dat, dat_multi, x))
Related