0

I have some code in R that invites a user to put in a year between 2010 and 2021.

chosen.year <- readline(promt = "choose year between 2010 and 2021:")
y.chosen.year <- paste("y", chosen.year)
year.input <- gsub(" ", "", y.chosen.year, fixed = TRUE)

The output that is stored in year.input is for e.g. 2015: y2015.

I have a dataframe for each year between 2010 and 2021 that is called y2010, y2011 etc.

Is it possible to later use year.input in another function that would otherwhise require me to write y2015 (so that the user can choose a year that will be used later on)?

Example:

myspdf2 <- merge(myspdf1, year.input, by.x "abc", by .y "def")

Instead of:

myspdf2 <- merge(myspdf1, y2015, by.x "abc", by .y "def")

I tried the method above but it did not work.

Remo Wyss
  • 31
  • 3
  • Please don't type untested code into your question: `readline(promt = "..")` is a syntax error, `Error in readline(promt = "..") : unused argument (promt = "...")`. (The fix is to fix spelling, `prompt=`.) It is tiresome *at best* to wade through problems that should trigger errors much sooner than what your question suggests. Please test your own code in a plain/new/empty R session: doing so ensures we don't have problems like this, makes sure you give us sample data for all variables used, and might in fact help you narrow down the culprit. – r2evans Feb 06 '22 at 17:36
  • I urge you to combine all of your `y*` frames into either (1) a single frame that has a `year` column; or (2) a [list of frames](https://stackoverflow.com/a/24376207/3358227), since you will typically be doing the same thing to all frames, enabling/benefiting-from `lapply` and company. The concept of `merge` is solely between two `data.frame`s, so your first code example is just wrong, and your second code example is lost on us since you've not discussed what `myspdf1` is. – r2evans Feb 06 '22 at 17:39

1 Answers1

0

Assuming promt= is not in your real code, two options:

  1. Combine all years into one frame, including the year in the data (if not there already).

    years <- ls(pattern = "^y\\d{4}$")
    allyears <- Map(
      function(x, yr) transform(x, year = yr),
      mget(years), years)
    subset(allyears, year == chosen.year)
    
  2. Combine all years into a list of frames, and subset from there:

    allyears <- mget(ls(pattern = "^y\\d{4}$"))
    allyears[[ chosen.year ]]
    

    (This assumes that a chosen.year will only reference one of the multiple frames.)

Ultimately I suspect that this is not about merge so much about subset (one-frame) or [[-extraction (list of frames).

A third option that I'm not fond of, but offered to round out the answer:

  1. Just get the data. BTW, you should use either paste0(.) or paste(., sep=""), otherwise you'll get y 2015 instead of y2015. This is much more direct than paste(.) and gsub(" ", "", .).

    year.input <- paste0("y", chosen.year)
    get(year.input)
    
r2evans
  • 141,215
  • 6
  • 77
  • 149