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

232 views Asked by At

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.

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

3

There are 3 answers

0
KnightofniDK On

An alternative approach to @user2974951 would be to save all the files in a list caled 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]
0
iod On

The for loop can be replaced with a 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.

1
user2974951 On

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