AMB
AMB

Reputation: 139

Using paste0 to fill in an argument

Let me start by saying I'm sure this has been answered before but I am unsure of what terms to search.

I have a few data frames that are named like df_A , df_B , and df_C and wish to send them all to ggplot. I tried to loop through them all but have been unsuccessful. Here is what I have now:

for (Param in c("A","B","C"){
  chosen_df <- paste0("df_",Param)
  ggplot(data=chosen_df...)
} 

I receive back an error saying "data must be a data frame". This error makes sense to me since chosen_df is character vector rather than the actual data frame.

I have tried using noquote but to no avail.

My questions are: 1) What kind of search terms can I look up to solve this problem 2) How close am I to solving this problem?

Upvotes: 1

Views: 270

Answers (1)

akrun
akrun

Reputation: 886938

We can use get to return the value of the object names as a string

for (Param in c("A","B","C"){
   chosen_df <- get(paste0("df_",Param))
    ggplot(data=chosen_df, ...)
  } 

Or with mget, return the values in a list

lst1 <- mget(ls(pattern = '^df_[A-Z]$'))

Upvotes: 4

Related Questions