[R] accessing files from subfolders

Duncan Murdoch murdoch.duncan at gmail.com
Wed Jun 8 23:53:20 CEST 2011


On 11-06-08 5:35 PM, J wrote:
> Hi,
>     There must be an easy way to do this, but I'm not finding it..
>
> I'd just like to know the syntax to move up and down folder levels, without necessarily entering a full file path.  Also, how to construct file and folder paths using variables.
>
> For example 1, if I wanted to print to the screen the contents of a file called myFile.txt using the bash shell, I'd use the following:
>
> cat ../myFile.txt
>
> Also, for example 2, if I want to cd into a folder that contains my files, from within a loop, where the counter serves as one of the folders in the path.
>
> In bash:
>
> for i in {1..5} A B C # A, B, and C are also folder names
> do
> cd ~/${i} # move into (change working directory to?) my folder of interest, which is 1,2,3,4,5,A,B,or C
> cat myFile.txt # print corresponding file of interest to screen
> cd - # move back to the previous folder
> done
>
>
> I wonder if there's an easy corresponding way to accomplish this in R.

The .. notation is supported on all platforms, as far as I know.  So to 
go to the parent of the current working dir, just use

setwd("..")

The ~ notation is not supported in all R functions, but setwd() supports 
it on all platforms, as far as I know.

Use file.path() to construct longer paths.

For your second example it would simply be setwd(file.path("~", i)).

Duncan Murdoch

>
> Any ideas most welcome!
>
> Jonathan
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list