Example files/directory
让我们创建一个包含一些示例文件的示例目录.这将让我们证明该解决方案是有效的,并且是可重复的解决方案的关键.
library(dplyr)
library(writexl)
library(readxl)
# Example directory with example files
dir.create(path = "KOMP")
write.csv(data.frame(x = 5), file = "KOMP/foo.csv")
write.csv(data.frame(x = 20), file = "KOMP/foo.nrrd.csv")
write.csv(data.frame(x = 1), file = "KOMP/foo2.nrrd.csv")
write.csv(data.frame(z = 2), file = "KOMP/bar.csv")
write.csv(data.frame(z = 5), file = "KOMP/bar.rrdr.csv")
# Example Excel file
write_xlsx(data.frame(name = c("foo", "hotdog")),
path = "KOMP/all_data.xlsx")
Solution
现在,我们可以使用我们的示例文件和目录来显示问题的解决方案.
# Get file paths in a data.frame for those that contain ".nrrd"
# Use data.frame() to avoid row names instead of as.data.frame()
# Need to use \\ to escape the period in the regular expression
file_names <- list.files(
path = "KOMP/",
pattern = "\\.nrrd",
all.files = TRUE,
full.names = TRUE,
recursive = TRUE
) %>%
data.frame(paths = .)
# Extract part of file name (i.e. removing directory substrings) that
# comes before .nrrd and add a column. Can get file name with basename()
# and use regular expressions for the other part.
file_names$match_string <- file_names %>%
pull(paths) %>%
basename() %>%
gsub(pattern = "\\.nrrd.*", replacement = "")
file_names$match_string
#> [1] "foo" "foo2"
# Read in excel file with file names to match (if possible)
name_data <- read_excel("KOMP/all_data.xlsx")
name_data$name
#> [1] "foo" "hotdog"
# Create match indicator and row number
name_data <- name_data %>%
mutate(
matched = case_when(name %in% file_names$match_string ~ 1,
TRUE ~ 0),
rowID = row_number()
)
# Create excel spreadsheet of files already downloaded
name_data %>%
filter(matched == 1) %>%
write_xlsx(path = "KOMP/already_downloaded.xlsx")