0

What I want to do is to set a value in R called "filename", with the content being the first part of a filename.

filename <- "E14_AD_4hr_"

I then want to use this 'filename' value to both name and call vectors that will be created through an R script.

Using the bash $ , the syntax would look something like this:

filename <- "E14_AD_4hr_"

$filename_Asz1 <- read.table("~/Documents/1608_10_MiSeq/untitled folder 2/E14-AD-4_S20_L001/Filtered_by_quality/E14-AD-4_S20_L001_Asz1/methylation.tsv", quote="\"", comment.char="") etc.

But this only gives me an error in R.

To get it to run the script correctly, I have to enter the first part of the filenames manually, which is a pain and very inelegant (there's more to the script, but I've only posted the first line).

E14_AD_4hr_Asz1 <- read.table("~/Documents/1608_10_MiSeq/untitled folder 2/E14-AD-4_S20_L001/Filtered_by_quality/E14-AD-4_S20_L001_Asz1/methylation.tsv", quote="\"", comment.char="")

Basically what I'm asking is does anyone know the correct syntax to set and call a name in this way, in R?

Thanks.

  • If we are reading multiple files, it is better to keep them in one list. Each data object within a list named as "Asz1, Asz2, AszN". See this [post](http://stackoverflow.com/questions/11433432/importing-multiple-csv-files-into-r) – zx8754 Sep 25 '16 at 19:35

1 Answers1

-2

I believe you're looking for assign.

prefix = "E14_AD_4hr_"

var_name = sprintf("%s_Asz1", prefix)
assign(var_name, read.table(...))

Note that if you invoke assign inside of a function, you might have to be careful about the environment you insert into. You can of course always assign to .GlobalEnv, or you could call parent.env() to jump one layer in the stack frame.

If you need to call those generated names later, you likely want parse and eval. For instance, if we store 10 random numbers in your variable name:

prefix = "E14_AD_4hr_"

var_name = sprintf("%s_Asz1", prefix)
assign(var_name, rnorm(10))

# Get the string value back
print(var_name)
[1] "E14_AD_4hr__Asz1"

# Convert to a language expression
> print(parse(text = var_name))
expression(E14_AD_4hr__Asz1)

# Evaluate in the current frame
> print(eval(parse(text = var_name)))
 [1] -0.31945098 -0.54377885 -0.27967344  1.06523260  1.56782875 -0.64311208  0.02052175 -0.32418446
 [9]  1.85739602  0.59076400
Michael Griffiths
  • 1,399
  • 7
  • 14