user391339
user391339

Reputation: 8785

How can I make a list of data files and data paths from branched folder locations?

I have data from 3 people in the following file path structure:

p1/ p2/ p3/ 

inside of each of the above are folders a/ and b/, which each contain the generically named data file I need to process datafile.txt

I need to load the data identifiers and locations into a list of the format:

p1
"p1/a/"
p1
"p1/b/"
p2
"p2/b/"
p3
"p3/a/"
p3
"p3/b/"

The tutorial document I am following uses something called sapply to navigate the file system, and the example does not accommodate branched data locations. I am very new to R so having trouble.

Upvotes: 0

Views: 91

Answers (1)

djas
djas

Reputation: 1023

If you must have a list (and not a vector), and assuming that myDir is the path where p1, p2, p3 are, then

tmp = dirname(list.files(myDir, recursive = T))
dirs = as.list(tmp)
names(dirs) = dirname(tmp)
dirs

$p1
[1] "p1/a"

$p2
[1] "p2/a"

$p2
[1] "p2/b"

$p3
[1] "p3/b"

If you actually want a vector, then

dirs = dirname(list.files(myDir, recursive = T))
names(dirs) = dirname(dirs)
dirs
p1     p2     p2     p3 
"p1/a" "p2/a" "p2/b" "p3/b" 

Upvotes: 1

Related Questions