【发布时间】:2020-09-14 18:38:05
【问题描述】:
我有一个包含多个工作表的 excel 文件,并将每个工作表分配给一个单独的变量。我决定尝试这样的 for 语句:
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(.)))
}
问题是我不知道如何在使用 assign() 后删除行。在将每张工作表分配给一个变量后,我想做一些清理并删除全部为 NA 的行。我尝试使用 paste0 和
更新:
使用列表:] 但如何删除每个数据框的最后 4 行?
x = 2
for (i in 1:6){
x <- x + 1
scoring_raw[[i]] <- read.xlsx(file.path(path,"Template.xlsx"), sheetIndex = x, colIndex = 1:5, startRow = 6, stringsAsFactors=FALSE) %>%
filter_all(any_vars(!is.na(.))) %>% #want to remove last 4 rows of dataframe
}
【问题讨论】:
-
如果您将所有对象保存在一个列表中而不是将它们分配给全局环境,这将容易得多。做你想做的最简单的方法是添加你的
filter_atinside分配,直接在read.xlsx之后。您可能还想查看函数get,它与assign相反 -
这能回答你的问题吗? Variable assignment within a for-loop
标签: r