简体   繁体   English

如何进入R中文件的目录?

[英]How to get into the directory of a file in R?

I have a directory "space" containing 300 CSV files, and its path is "C://rstuff//space". 我有一个包含300个CSV文件的目录“空间”,其路径为“ C:// rstuff // space”。

And I have a function: 我有一个功能:

myfunction <- function(my_dir, x, y){

      }

I want to open some of the csv files, so I want to get the location of these files,and I use the argument 'my_dir' to indicate the location of the CSV files. 我想打开一些csv文件,所以我想获取这些文件的位置,并使用参数“ my_dir”来指示CSV文件的位置。 I want to use setwd(paste0("C://rstuff//", my_dir)) (thanks for Batanichek's comment), but I think my way is not good to set the path, if I don't know the path exactly, what should I do? 我想使用setwd(paste0(“ C:// rstuff //”,my_dir))(感谢Batanichek的评论),但是我认为我的方法不好设置路径,如果我不完全知道路径的话, 我该怎么办? Is there any good methods? 有什么好的方法吗?

You can use list.files 您可以使用list.files

setwd("C://rstuff//space")
my_files<-list.files(pattern = ".csv", 
                     full.names = TRUE, recursive = TRUE, ignore.case = TRUE)

This finds all csv files in your working directory and give you the path starting from your working directory. 这会在您的工作目录中找到所有csv文件,并为您提供从工作目录开始的路径。

 [1] "./csvs2/data_1-10.csv"         
 [2] "./csvs2/old/data_1001-1010.csv"
 [3] "./overview/results.csv"

Then you can specify the ones you want to use. 然后,您可以指定要使用的那些。 I for example give the important csv files a number after an "_" eg "data_23". 例如,我给重要的csv文件一个“ _”后面的数字,例如“ data_23”。 So you can exclude all non-important files with: 因此,您可以使用以下命令排除所有不重要的文件:

my_files<-my_files[-(which(grepl("_", my_files)==FALSE))]

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

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