[R] Is there an easier way to replace the object name in the R code

Erik Iverson eriki at ccbr.umn.edu
Wed May 12 06:18:02 CEST 2010

mam3xs wrote:
> Hi all,
> I have a R code with quite a few lines.  For instance
> AA <- read.csv(C:\\AA.txt)
> AA.diff <- diff(log(AA))
> .....
> ....
> Now I want to re-define the code with different object, like BB,
> CC......ZZ(the codes are the same). Thus, I was wondering whether their is
> an efficient way or automatic way to replace and generate new objects rather
> than using "find and replace" function in txt/word manually....?

Defining your own functions, using lists, and lapply would work just great most 

Untested, but something like should work:

#create list of all file names
files <- sapply(LETTERS, function(x) paste(x,x, sep = "", collapse = ""))

#read in the files into a list.
my.list <- lapply(files, function(x)
    read.csv(paste("C:\\", x, ".txt", sep = ""))

#apply a function to each item in the list
lapply(my.list, function(x) diff(log(x)))

More information about the R-help mailing list