Reputation: 299
I am very new to programming with R, but I am trying to read in multiple files for a directory and give them each a unique name. I am reading the files in using the Dendrochronology Program Library in R (package dpIR) and the read.tucson
function. Although I'm using a specific package, I think my question is fairly general:
Within the loop, I want to create files by concatenating a "t"
with each individual files name. So, if I have a file named "2503"
in my directory, I want to create a dataframe in R called "t2503"
. Next, I want to read the data in using the r.tucson
function to each dataframe. Rather than assigning the read-in data to the dataframe, I'm just overwriting the concatenation with the data. Can someone help me figure out what step I am missing?
Here is the code I am trying to use:
#set to appropriate directory
setwd("C:/work")
#get a list of files in the directory
files <- list.files()
numfiles <- length(files)
for (i in 1:numfiles)
{
name<-paste("t",files[i],sep="")
name<-read.tucson(files[i],header=NULL)
}
Upvotes: 22
Views: 66547
Reputation: 6884
I think you gave the answer yourself: you have to use ?assign
.
Try something like that:
for (i in 1:5) {
assign(paste0("DF", i), data.frame(A=rnorm(10), B=rnorm(10)))
}
This loops through the integers from 1 to 5 and creates five data.frames "DF1" to "DF5". For your example, you should just replace
name<-read.tucson(files[i],header=NULL)
with
assign(name, read.tucson(files[i],header=NULL))
Note, however, that name
is a base function in R, so I would use another naming convention or just skip the first line:
assign(paste("t",files[i],sep=""), read.tucson(files[i],header=NULL))
I hope this is what you are looking for.
Upvotes: 35