R- how to dynamically name data frames? [duplicate]
OP is really struggling so instead of a long comment, I'll show him here. Don't care if this gets closed.
The technical (don't do that answer) would be to use assign
:
i <- 1
j <- 1
for (f in 1:length(fileList)){
fileName <- fileList[f]
X <-read.xls(fileName)
if(grepl("Drug_Rep", fileName)) {
print("DRUG")
print(fileName)
assign(paste("X_Drug_Rep", i, sep = '_'), X)
i <- i+1
} else {
print("CONTROL")
print(fileName)
assign(paste("X_CONTROL", i, sep = '_'), X)
j <- j+1
}
}
But as we recommended, you should use lists instead. Using a for
loop, it would look like this:
X_Drug_Rep <- list()
X_CONTROL <- list()
i <- 1
j <- 1
for (f in 1:length(fileList)){
fileName <- fileList[f]
X <-read.xls(fileName)
if(grepl("Drug_Rep", fileName)) {
print("DRUG")
print(fileName)
X_Drug_Rep[[i]] <- X
i <- i+1
} else {
print("CONTROL")
print(fileName)
X_CONTROL[[j]] <- X
j <- j+1
}
}
Finally, how your code would look like without a for
loop:
drug.rep.files <- grep("Drug_Rep", fileList, value = TRUE)
control.files <- grep("Drug_Rep", fileList, value = TRUE, invert = TRUE)
X_Drug_Rep <- lapply(drug.rep.files, read.xls)
X_CONTROL <- lapply(control.files, read.xls)
Much shorter, no?! Again, this creates two lists. For example, instead of X_Drug_Rep_1
, you would access the first Drug_Rep item by doing X_Drug_Rep[[1]]
.