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

杀马特。学长 韩版系。学妹 提交于 2020-01-11 15:42:07

问题


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)
}

回答1:


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.



来源:https://stackoverflow.com/questions/13940478/how-do-i-rename-a-data-frame-in-a-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!