R - how to dynamically name data frames?

I have two types of files in my directory. Each type has either the text "Drug_Rep" in it, or if it is not there, it means its control file. Drug data have replications that can vary in quantity, as well as control. I read the files in a for loop as follows. I want to name my data as X_Drug_Rep1, and then the next as X_Drug_Rep2, etc .... and save the data frame for further processing. Do the same for the controls ... X_CONTROL_Rep1 ... X_CONTROL_Rep2 ... and so on. What is the syntax for storing my data in dataframes, because I need to do some merging and computing later when the replicated data will be processed separately. the paste on the left side of the job does not work. Any suggestions?

for (f in 1:length(fileList)){ fileName <- fileList[f] X <-read.xls(fileName) if(regexpr("Drug_Rep", fileName)[1]>0){ print("DRUG") print(fileName) paste(X_Drug_Rep,i)<-X i=i+1 } else{ print("CONTROL") print(fileName) paste(X_CONTROL,j)<-X j=j+1 } } 
+4
source share
1 answer

OP really fights, so instead of a long comment, I will show it here. Don't care if it closes.

A technical (don't do this answer) would have 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 will 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, what your code looks 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 will gain access to the first Drug_Rep element by executing X_Drug_Rep[[1]] .

+13
source

Source: https://habr.com/ru/post/1487659/


All Articles