for循环特定文件名R.

时间:2018-02-28 14:50:18

标签: r for-loop nested-loops file-copying

我有一个标识符列表保存为字符变量(uid_car) 我有一个文件列表(file_list),标识符作为文件名的前缀(例如1000 _ * .file)

uid_car< -1000,1002,1004 .... LEN(170) file_list中< -1000_01_.file,1001_02.file,1003_02.file,1002_01.file,1004_01.file ... LEN(〜700)

在上面的示例中,我想循环遍历文件列表并复制具有uid_car中包含的前缀的文件。因此,只有文件1000_01.file,1002_01.file和1004_01.file才会被复制到新路径。

以下for循环适用于你点击uid_car中未包含的第i个元素。

我尝试过一个可能有点整洁的mapply功能,但是没有多少经验写这些......任何帮助都会受到赞赏。

for (i in length_of_file_list) {
  if (startsWith(file_list[i], uid_car[])) {
    file.copy(file_list[i], new_path)
  }
}

2 个答案:

答案 0 :(得分:1)

如果你想在一个循环中这样做,这可能会做你想要的:

uids_to_print <- c("1000", "1001", "1004")
filenames <-c("1000_01.file","1000_02.file","1001_01.file","1001_02.file","1002_01.file","1002_02.file","1003_01.file","1004_01.file")


# Iterate through each filename
for (filename in filenames) {

    # Pull out the characters prior to the first underscore
    filename_uid <- unlist(strsplit(filename, "_"))[1]

    # Cheeck if it's in the list of ones to print
    if(filename_uid %in% uids_to_print) {
        # Put file operation inside this loop

    }
}

例如,执行

for (filename in filenames) {
    filename_uid <- unlist(strsplit(filename, "_"))[1]
    if(filename_uid %in% uids_to_print) {
        print(paste("copy", filename, sep=" "))
    }
}

产量

"copy 1000_01.file"
"copy 1000_02.file"
"copy 1001_01.file"
"copy 1001_02.file"
"copy 1004_01.file"

答案 1 :(得分:0)

我认为你不需要循环。

files.to.copy <- file_list[file_list %in% paste0(uid_car,'_01.file')]
file.copy(files.to.copy, new_path)