如何在for循环中重命名数据帧 [英] How do I rename a data-frame in a for-loop

查看:163
本文介绍了如何在for循环中重命名数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用R编程我很新,但我正在尝试在多个文件中读取一个目录,并为它们分配一个唯一的名称。我正在使用R(包dpIR)和 read.tucson 函数中的树木年代学程序库读取文件。虽然我使用的是特定的包,但我想我的问题是相当普遍的:

在循环中,我想通过连接 t与每个单独的文件名称。所以,如果我的目录中有一个名为2503的文件,我想在R中创建一个名为t2503。接下来,我想读取使用 r.tucson 函数到每个数据帧的数据。而不是分配读入数据到数据帧,我只是用数据覆盖连接。有人可以帮我找出我失踪的步骤吗?

这是我想要使用的代码:

  #set到适当的目录
setwd(C:/ work)

#获取目录中的文件列表
文件< --list.files()
numfiles< - 长度(文件)

for(i in 1:numfiles)
{
name< -paste (t,files [i],sep =)
name< -read.tucson(files [i],header = NULL)
}


解决方案

我想你自己给了答案:你必须使用?assign



尝试类似的方法:

  assign(paste0(DF,i),data.frame(A = rnorm(10),B = rnorm(10)))
}



循环遍历从1到5的整数,并创建五个数据框架DF1到DF5 。对于你的例子,你应该只替换

  name< -read.tucson(files [i],header = NULL)



  assign(name,read.tucson(files [i],header = NULL))

,但是, name 是R中的一个基本函数,所以我会使用另一个命名约定或者跳过第一行:
$ b $ (b)($ t $ t $ t $ t $ t $ t $ t $ t $ t $ t $

我希望这就是您要找的。

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

解决方案

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.

这篇关于如何在for循环中重命名数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆