1

I have a for loop that assigns multiple data frames in different values and it works by itself. But when I try to create a function with this for loop, it doesn't work. On top of assigning different names to different data frames, I'm also trying to create a vector that keeps the names of these dataframes, but seems like this function doesn't save "dfnames"

create_df <- function(name){
dfnames <- c() 
  for(i in name){
     assign(paste0("subject", i, sep = "_"), passive_subject(i))
     dfnames <- c(dfnames, paste0("subject", i, sep = "_"))
     dfnames
     } 
}

How can I go about this?

5
  • What is passive_subject Commented Jun 28, 2021 at 19:45
  • Are you assign ing objects to global env Commented Jun 28, 2021 at 19:47
  • 2
    you should not use assign for something like this. Use a list instead. See dww's answer. Commented Jun 28, 2021 at 19:54
  • 1
    You are creating a mess. The various subject_n objects are not in a list and are separate from the collection of their names. It's not surprising that you are not getting what you want. You shoudl be creating a list with names, rather than a bunch of separate objects and a separate naming vector. You should change the checkmark to award @dww Commented Jun 29, 2021 at 22:59
  • Voting to close because it remains very unclear what was intended because the is nominimal reproducible example or even a good description of the data inputs. Commented Jun 30, 2021 at 4:53

2 Answers 2

3

It would almost certainly be better to return a list of the data frames, and set the names of that list. In general this is a tidier approach than having lots of similar data.frames as separate objects.

create_df <- function(name){
   l = lapply(name, passive_subject)
   names(l) = paste0("subject", name, sep = "_")
   return(l)
}
Sign up to request clarification or add additional context in comments.

Comments

-2

In the function, there is no return value. We can add the return value and it works.

create_df <- function(name){
   dfnames <- c() 
   for(i in name){
     assign(paste0("subject", i, sep = "_"), passive_subject(i), 
           envir = .GlobalEnv)
     dfnames <- c(dfnames, paste0("subject", i, sep = "_"))
     
     } 
   return(dfnames)
}

8 Comments

is there a way to run dfnames anytime? because right now the names show when I run the whole function but I hope to run dfnames by itself sometimes
I didn't understand your question. Inside the function, you are creating the dfnames as a NULL element c()
Returning the names vector did nothing to return the subject_n values.
@IRTFM Please look at OP's question - but seems like this function doesn't save "dfnames".
This is an example from today's Q&A that shows the correct way (obviously in my opinion) to respond in such situations: stackoverflow.com/questions/68198745/for-loop-with-dplyr
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.