简体   繁体   English

如何在for循环中为数据帧分配名称? 在R中

[英]How to assign name to data frames in a for loop? In R

I have 10 files, for simplicity let's call them A: J. I wish to read them in using a for loop that reads them in and assigns them a name from a vector of names. 我有10个文件,为简单起见,我们称它们为A:J。我希望使用for循环读取它们,并读取它们并从名称向量中为它们分配一个名称。

This is my code: 这是我的代码:

i=1:10
name<-c("A", "B", "C", "D", "E", "F","G","H","I","J")
file<-c("A.txt", "B.txt", "C.txt", "D.txt", "E.txt",        
"F.txt","G.txt","H.txt","I.txt","J.txt")

for (i in 1:7){
tmp<-read.table(file[i],sep="\t",header=TRUE) %>% 
assign(name[i])
} 

This results in: Error in assign(., species[i]) : invalid first argument 结果导致: Error in assign(., species[i]) : invalid first argument

There are a couple of wrong things here, I am assuming species is some sort of vector from tmp, if so you need to reference that. 这里有一些错误的事情,我假设物种是tmp的某种矢量,如果需要的话,您需要引用它。 You also forgot to assign a variable name 您还忘记分配变量名

name<-c("A", "B", "C", "D", "E", "F","G","H","I","J")
file<-c("A.txt", "B.txt", "C.txt", "D.txt", "E.txt",        
        "F.txt","G.txt","H.txt","I.txt","J.txt")

for (i in 1:10){
  tmp<-read.table(file[i],sep="\t",header=TRUE)
  assign(paste0("v",i),species[i])
} 

An alternative approach to @user2974951 would be to save all the files in a list caled dataFiles. @ user2974951的替代方法是将所有文件保存在列表校准的dataFiles中。

name<-c("A", "B", "C", "D", "E", "F","G","H","I","J")
file<-c("A.txt", "B.txt", "C.txt", "D.txt", "E.txt",        
        "F.txt","G.txt","H.txt","I.txt","J.txt")

dataFiles = list()
for(i in 1:length(file)) {
  dataFiles[[LETTERS[i]]] = read.table(file[i],sep="\t",header=TRUE)
}

> names(dataFiles)
 [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J"

I here use LETTERS to assign names, but could be just as well be: 我在这里使用字母来分配名称,但也可能是:

name[i]

The for loop can be replaced with a sapply : for循环可以替换为sapply

dat<-sapply(name,function(x) assign(x,read.table(paste0(x,".txt"),,sep="\t",header=TRUE)), USE.NAMES=TRUE, simplify=FALSE)

This creates a single list (called "dat") with each element in it named using the elements of "name" and containing the table in the file (name).txt. 这将创建一个列表(称为“ dat”),列表中的每个元素都使用“ name”元素命名,并将表包含在文件(name).txt中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM