我有一个嵌套的for loop
情况,我正在循环遍历几个excel工作表,应用多个函数,从每个工作表生成单个 data.frame
,并编写所有回到新工作簿,其工作表名称与原始工作簿相同。
目前新工作簿中的工作表名称正确,但data frames
继续相互书写,以便每张工作表都具有相同的data frame
。如何让每个data frame
写入相应的Excel工作表?
library(xlsx)
library(agricolae)
#Read all worksheets in one file
read_excel_allsheets <- function(filename) {
sheets <- readxl::excel_sheets(filename)
x <- lapply(sheets, function(X) readxl::read_excel(filename, sheet = X))
names(x) <- sheets
x
}
mysheets <- read_excel_allsheets("Loop_help.xls")`
for (i in 1:length(mysheets)){ #loop through sheets in workbook
file<-as.data.frame(mysheets[i])
for(i in 2:ncol(file)){ #loop through columns in sheets
if(var(file[,i]) > 0){ #exclude columns that are all zeros
#create data frame (df)
#do stuff
}
#dostuff
}
#do more stuff
n<-excel_sheets("Loop_help.xls") #sheet names
for (i in 1:length(mysheets)) {#write new sheets to excel
if (i == 1)
write.xlsx(df, file="Loop.Help.xls", sheetName = n[i])
else write.xlsx(df, file="Loop.Help.xls", sheetName = n[i],
append = TRUE)
}
}
答案 0 :(得分:0)
感谢@Parfait引导我回答这个问题。
我不仅有一个多余的for loop
,而且我在两个循环中调用i
,当我需要使用另一个字母(k
)时。
以下是最终代码:
for (k in 1:length(mysheets)){#loop through sheets in workbook
file<-as.data.frame(mysheets[k])
for(i in 2:ncol(file)){#loop through columns in sheets
if(var(file[,i]) > 0){#exclude columns that are all zeros
#create data frame (df)
#do stuff
}
}
#do more stuff
n<-excel_sheets("Loop_help.xls") #sheet names
if (k == 1)
write.xlsx(df, file="Loop.help.xls", sheetName = n[k])#write first sheet
else write.xlsx(df, file="Loop.help.xls", sheetName = n[k],
append = TRUE) #append additional sheets
}