[R] Naming files within R code

Andrew Simmons @kw@|mmo @end|ng |rom gm@||@com
Sun Mar 20 23:24:41 CET 2022


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 using gmail.com> wrote:

> Hello    I have data from various Scottish river catchments in the form of
> csv files.  I want to be able to download the files in turn and refer to
> each one by an assigned name from a vector of names, but within R.  So, for
> example, if my vector of names is c("tay","forth","don") I want to tell R
> to refer to the sequences of dataframes as a variable name, ie the table
> uploaded from the first csv becomes the object tay *within* R and so on, so
> that I could the do things like write print(tay[,1]) etc,rather than having
> to refer to a list eg print(riverlist[[1]][,1])  I don't know whether this
> is possible but if it is I'd be grateful for any pointers
> Thanks, Nick Wray
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list