在for循环中创建变量并赋值
我有一个包含多个工作表的excel文件,并将每个工作表分配给一个单独的变量。我决定尝试这样一种说法:在for循环中创建变量并赋值,r,R,我有一个包含多个工作表的excel文件,并将每个工作表分配给一个单独的变量。我决定尝试这样一种说法: x = 2 for (i in 1:6){ x <- x + 1 assign(paste0(i,"_file"), read.xlsx(file.path(path,"Template.xlsx"), sheetIndex = x, colIndex = 1:5, startRow = 6, stringsAsFactors=FALSE
x = 2
for (i in 1:6){
x <- x + 1
assign(paste0(i,"_file"), read.xlsx(file.path(path,"Template.xlsx"), sheetIndex = x, colIndex = 1:5, startRow = 6, stringsAsFactors=FALSE)
)
#remove rows where the entire row is NA (do not remove rows that have some values and/or NA, has to be completely NA)
paste0(i,"_file")<- paste0(i,"_file") %>% filter_at(colnames(paste0(i,"_file")), any_vars(!is.na(.)))
}
x=2
(我在1:6中){
x虽然@Parfait是完全正确的,您应该更喜欢使用list,但这里有一种可能性可以回答您的问题,使用eval
和parse
。但是您需要将索引i
放在对象名称的末尾,而不是开头,以避免出现问题:
x = 2
for (i in 1:6){
x <- x + 1
assign(paste0("file_",i), read.xlsx(file.path(path,"Template.xlsx"), sheetIndex = x, colIndex = 1:5, startRow = 6, stringsAsFactors=FALSE)
)
#remove rows where the entire row is NA (do not remove rows that have some values and/or NA, has to be completely NA)
assign(paste0("file_",i),
eval(parse(text = paste0("file_",i))) %>%
filter_all(any_vars(!is.na(.)))
}
如果您将所有对象都保存在一个列表中,而不是将它们分配给全局环境,那么这将容易得多。最简单的方法是在分配中添加过滤器,直接在read.xlsx
之后这是否回答了您的问题?谢谢,您知道如何从%>%之后的数据框中删除最后4行吗?我已更新了上面的问题
x = 2
for (i in 1:6){
x <- x + 1
assign(paste0("file_",i), read.xlsx(file.path(path,"Template.xlsx"), sheetIndex = x, colIndex = 1:5, startRow = 6, stringsAsFactors=FALSE)
)
#remove rows where the entire row is NA (do not remove rows that have some values and/or NA, has to be completely NA)
assign(paste0("file_",i),
eval(parse(text = paste0("file_",i))) %>%
filter_all(any_vars(!is.na(.)))
}
for (i in 1:6){
x <- x + 1
assign(paste0("file_",i),
read.xlsx(file.path(path,"Template.xlsx"), sheetIndex = x, colIndex = 1:5, startRow = 6, stringsAsFactors=FALSE) %>%
filter_all(any_vars(!is.na(.)))
)
}