Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I rename a data-frame in a for-loop

Tags:

for-loop

r

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)
}
like image 368
user1913921 Avatar asked Dec 18 '12 19:12

user1913921


People also ask

How do I rename a column in pandas for loop?

One way of renaming the columns in a Pandas Dataframe is by using the rename() function.

How do you name a data frame in a list?

You can also use a setNames() function within a Map() function to rename each column for your list of dataframes. To keep your code clean as possible, it is best to avoid naming objects with the same names as functions. (Your example code uses a vector called "names" but also uses names() function.)

How do you make a loop in a Dataframe in R?

A data frame can also be created row by row, using repeated rbind() operations on the data frame in the for loop, with number of iterations equivalent to the number of rows to insert.


1 Answers

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.

like image 82
Christoph_J Avatar answered Sep 17 '22 01:09

Christoph_J