【发布时间】:2016-11-21 10:59:07
【问题描述】:
我在编写一个函数以读取多个 .xlsx 文件作为 R 中的单独数据帧和 for 循环时遇到了一些麻烦。当我运行该功能时,没有任何反应。没有错误,但也没有数据帧加载到 R 中。当我从函数中取出分配块并手动将输入从 for 循环更改为示例时,分配函数起作用。下面是代码示例:
library(readxl)
Load<-function(File_Path,Samp){
setwd(File_Path)
for (i in 1:length(Samp)){
assign(paste("Sample_",Samp[i],sep = ""),read_excel(paste("Sample_",Samp[i],".xlsx",sep = "")))
}
}
Load(File_Path = "~/Desktop/Test",Samp = "A") # Doesn't Work
#When this piece is taken out of the loop and the Sample ("A") replaced it works.
assign(paste("Sample_","A",sep = ""),read_excel(paste("Sample_","A",".xlsx",sep = ""))) # Does Work
实际上,有很长的样本列表要加载,并且希望通过为“Samp”分配一个列表来加载,例如 c("A","C","D")。预先感谢您的任何帮助。
【问题讨论】:
-
问题是
assign使用它被调用的环境,因此在函数中使用它会在函数环境而不是全局环境中分配它。该函数也不返回任何内容。您应该考虑另一种方法,但如果您真的想使用assign,请参阅我的回答
标签: r for-loop import xlsx assign