Skip to content
Prev 391065 / 398506 Next

Naming files within R code

It's definitely possible to create R objects without knowing their names
using 'assign', but this is considered bad practice. For example,
assign("tay", riverlist[["tay"]])
And you could put that in a for loop, looping through the names of your
files.

You could consider using 'attach'. You would write something like
attach(riverlist) and it would assign your variables into a new environment
and put it on your search list. Only problem is that modifying these
objects will (generally) create new objects, and not modify the originals.
For example, tay[[1]] <- NA
will create a new variable tay in your global environment, and not modify
the variable in your
riverlist environment. Maybe that's how you want it to work, up to you.

In general though, I would say that making variables in either of these
manners is setting yourself up for failure. It is much better to do
tay <- read.csv(...)
forth <- read.csv(...)
...

One final solution is to do what you're currently doing, but use names to
refer to a data frame in a list, instead of integers.
For example, if your csv files are "tay.csv", "forth.csv", and "don.csv",
and you had those strings stored in a variable 'riverfiles'
then remove the .csv and give the riverlist some names like
names(riverlist) <- sub("[.]csv$", "", riverfiles)
I hope this helps.
On Sun, Mar 20, 2022, 18:03 Nick Wray <nickmwray at gmail.com> wrote: