简体   繁体   English

R:通过在多个计算机目录中查找来命名多个列表

[英]R: Name multiple lists from looking within multiple computer directories

I wonder whether R can do this: 我想知道R是否可以做到这一点:

I have several tens of folders on my C: drive within C:/Names. 我在C:/名称中的C:驱动器上有几十个文件夹。 For simplicity sake, say there's only two called "Ben" and "Dave". 为了简单起见,假设只有两个分别称为“ Ben”和“ Dave”。 Each one of these folders has several files. 这些文件夹中的每个都有几个文件。

I want R to create a list of those files for each folder and then assign the list the name of that folder. 我希望R为每个文件夹创建这些文件的列表,然后为该列表分配该文件夹的名称。 So the result would give me two separate objects something like: 因此,结果将为我提供两个类似的对象:

Ben:

[1] "File1.csv" "File2.csv"  

Dave:
 [1] "File3.csv" "File4.csv

I feel like I'd have to loop it to do so but with my limited knowledge, not really sure how. 我觉得我必须循环执行此操作,但是由于我的知识有限,还不确定如何操作。 I want to do this for all the folders within C:/Names and not just for the two in the example. 我想对C:/ Names中的所有文件夹执行此操作,而不仅仅是对示例中的两个文件夹执行此操作。

Is this what you are looking to do? 这是您要做什么?

names <- "C:/Names"
folders <- list.dirs(path = names, full.names = F, recursive = F)
for (foldersA in folders){
  assign(foldersA, list.files(paste(names, foldersA, sep="/")))
}

Generally it's a bad idea to create objects with arbitrary names because there's the possibility that one of the subfolders will have a name that isn't legal for an object in R, or overwrites an existing object. 通常,用任意名称创建对象是一个坏主意,因为子文件夹之一的名称可能对R中的对象不合法或覆盖现有对象。 The more R-ish way to do that is to create a single list using: 更多的R-ish方法是使用以下方法创建一个列表:

input.names <- lapply(list.dirs("c:\\Names"),list.files)

then you can either loop over the elements of the list for further processing, or access individual elements as input.names$Dave or input.names[["Dave"]] . 那么您可以在列表中的元素上循环以进行进一步处理,或者将单个元素作为input.names$Daveinput.names[["Dave"]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM