0

I'm creating a function to that several data frames automatically. How can I call those data.frames to mutate them?

For example, say I created a data for which each item is meant to become a dataframe like so:

assign(paste0("d","f"),c(tree,fox,river))

Then I take an item from the list and use it to name a dataframe.

assign(paste(get(paste0("d","f"))[1]),as.data.frame(c(1,2,3))

so that now if i do:

get(paste(get(paste0("d","f"))[1]))

it returns a data frame with 1,2,3

Here's my problem, I want to be able to modify those items so something like

get(paste(get(paste0("d","f"))[1]))[1] <- 4

#So that now if i do

get(paste(get(paste0("d","f"))[1]))

it returns a data frame with 4,2,3

  • 3
    Can you explain a little more about what you are trying to accomplish in the bigger picture? This feels like an [`XY Problem`](https://www.perlmonks.org/index.pl?node_id=542341) – JasonAizkalns Oct 04 '19 at 17:20
  • 2
    I strongly suggest you re-write your code not to depend on [get/assign](https://stackoverflow.com/questions/17559390/why-is-using-assign-bad). Typically just using named lists will save you a lot of code/effort. – MrFlick Oct 04 '19 at 17:36
  • The bigger picture is that I have an excel sheet with multiple sheets and I am trying create a function that automatically imports each sheet as a separate data.frame and renames them based on the sheet name, add a column specifying which sheet a row came from, and then merges all those dataframes. – Tare Suriel Oct 04 '19 at 17:45

1 Answers1

2

It is better not to create multiple objects in the global environment. If it is already created, load them into a list and do all the changes/transformations/mutates etc. in the list. It would make easier to read/write in list rather than looking for these objects floating in the global env

lapply(mget(paste0("df", 1:3)), function(x) {x[[1]] <- 4; x})
akrun
  • 874,273
  • 37
  • 540
  • 662