我正在使用此代码在一系列数据帧上执行相同的操作。一切似乎都运行正常,直到我尝试用两个.Rda
文件中的不同变量保存每个数据框。
问题是我最终得到了两个.Rda
文件,其中包含数据框的变量名称,但这些变量的内容完全相同。似乎只适用于variables
的最后一个数据框。我认为它与循环有关,但我不知道如何解决这个问题。
#Previous steps, loading files...
setwd("path_to_files")
list.files()
files <- list.files(pattern = "toptable")
envar <- new.env()
#Load all files
for (i in files){load(i, envir = envar)}
varName <- ls(envar)
rm(i)
attach(envar)
variables <- as.list(envar)
#From now on the function
setwd("/path_to_save")
filtering_data <- function(x){
#In here I'm just filtering data frames by certain values of it's columns (P.Value column and t column)
x <- as.data.frame(x)
pval <- which(x$P.Value < 0.05)
pval <- x[pval,]
up.pval <- which(pval$t > 0)
down.pval <- which(pval$t < 0)
up.pval <- pval[up.pval,]
down.pval <- pval[down.pval,]
#Modify names to use them as variable names when saving
up_varNames <- paste0(varName, ".", "up")
down_varNames <- paste0(varName, ".", "down")
for (i in seq_along(up_varNames)){
assign(up_varNames[i], up.pval)
assign(down_varNames[i], down.pval)
}
save(list = up_varNames, file = "up.Rda" )
save(list = down_varNames, file = "down.Rda" )
}
#function
lapply(variables, filtering_data)
detach(envar)