0

Lets say I have 5 dataframes and I want to create a list of them based on their name (just like we can filter columns and rows based on name or similarities to a word).

Example:

df1 <- data.frame(Y = rnorm(15), Z = rnorm(15))
df2 <- data.frame(Y = rnorm(15), Z = rnorm(15))
df3 <- data.frame(Y = rnorm(15), Z = rnorm(15))

specialdf1 <- data.frame(Y = rnorm(15), Z = rnorm(15))
specialdf2 <- data.frame(Y = rnorm(15), Z = rnorm(15))
specialdf3 <- data.frame(Y = rnorm(15), Z = rnorm(15))

speciallist <- list(specialdf1, specialdf2, specialdf3)

Instead of doing this by hand I want to call the dataframes by something they have in their name (e.g. "special") AND not be limited to e.g. 3 dataframes (since I would not know how many dataframes will be there in actuality). How would I do this?

  • 1
    Try `mget(ls(pattern = 'specialdf[0-9]+'))` – Sotos Jun 10 '21 at 08:14
  • 2
    adding to what @Sotos have: `mget(ls(pattern = 'special'), mode = 'list')` – Onyambu Jun 10 '21 at 08:15
  • Good thinking @Onyambu. Eventhough `list` is the default, it is still useful to show – Sotos Jun 10 '21 at 08:17
  • @Sotos no. list is not the default. I believe `any` is the default. meaning if you have a character/string called special123char, it will be captured. But OP only needs dataframes – Onyambu Jun 10 '21 at 08:18
  • True. I was referring to the object (being df) – Sotos Jun 10 '21 at 08:26
  • Hi thank you both, for some reason it only accepts it if I write it until at least the last underscore in the case of a long name with multiple underscores, e.g.: ```plots_list <- mget(ls(pattern = 'specialdf_NM_[0-20]+'))```. Can someone answer it so I can write it as solved / what should I do? – Luckystrikerr Jun 10 '21 at 08:27
  • 1
    I m sure this is a duplicated question so I will look for it and close this one. No worries, you dont need to do anything :) – Sotos Jun 10 '21 at 08:52
  • Thank you, I'm probably a bit too new to R to know how to look more specific for some questions (I did try :)) – Luckystrikerr Jun 10 '21 at 11:31

0 Answers0