Imogen
Imogen

Reputation: 1

Trying to create dataframe from list of files (in nested directories) containing separate columns for each folder

I am relatively new to R and working on some cameratrap image data for my dissertation. I've got a folder containing 29 folders, each representing a woodland site, with different subfolders representing locations and sampling periods.

I have created a list (?) in R using

files <- list.files(full.names = TRUE, recursive = TRUE, include.dirs =TRUE)

that now gives me "values" for each image looking like this:

"./1780/Location1/Check_19.11.19/IMG_0171.JPG"

I would now like to turn this into a dataframe and separate it into discrete columns, so I have one for "site" (example 1780) one for Location (values will always be 1 or 2) one for "time period" (i.e.Check_19.11.19) and one for the image file name. This is so that I can attach ID tags manually in another column. I have no idea if this is the correct way to do this, I am sure there is a more elegant way, but I haven't found it yet.

If I have overlooked an already existing answer, feel free to direct me to that. Thank you for your help!

Upvotes: 0

Views: 794

Answers (2)

Iroha
Iroha

Reputation: 34761

A simple approach would be to use read.table(), trimming the entries with substring() first.

read.table(text = substring(files, 3), sep = "/", col.names = c("site", "location", "time","filename"))

Upvotes: 1

jyr
jyr

Reputation: 692

This can be done with function separate from tidyr. Check documentation for more information.

  library(tidyr)
  library(dplyr)

  files <- list()
  files[1] <- "./1780/Location1/Check_19.11.19/IMG_0171.JPG"
  files[2] <- "./1780/Location2/Check_19.12.19/IMG_0171.JPG"


  df <- data.frame(column= unlist(files)) %>% 
           separate(column, sep="/", into=c("x","site", "location", "time","filename")) %>% 
           select(-x)

or

files <- gsub("^./","",files)
df <- data.frame(column= unlist(files)) %>% 
         separate(column, sep="/", into=c("site", "location", "time","filename"))

Upvotes: 2

Related Questions