variables - R- how to dynamically name data frames? -
variables - R- how to dynamically name data frames? -
this question has reply here:
how assign values dynamic names variables in r 3 answersi have 2 types of files in directory. each type has either text "drug_rep" in or if not there means command file. drug info has replicates can vary in number , control. reading files in loop follows. want name dataframes x_drug_rep1 , next x_drug_rep2 , on...and save dataframe farther processing. same controls...x_control_rep1...x_control_rep2...and on. syntax save info dataframes because need merges , calculations later on drug replicate dataframes , controls separately. paste on left side of assignment not seem work. 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 } }
op struggling instead of long comment, i'll show him here. don't care if gets closed.
the technical (don't answer) utilize assign
:
i <- 1 j <- 1 (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+1 } else { print("control") print(filename) assign(paste("x_control", i, sep = '_'), x) j <- j+1 } }
but recommended, should utilize lists instead. using for
loop, this:
x_drug_rep <- list() x_control <- list() <- 1 j <- 1 (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+1 } else { print("control") print(filename) x_control[[j]] <- x j <- j+1 } }
finally, how code without 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, creates 2 lists. example, instead of x_drug_rep_1
, access first drug_rep item doing x_drug_rep[[1]]
.
r variables dynamic data.frame
Comments
Post a Comment