Pre-requisites in R

Make sure you have the necessary packages installed.

# Installs and loads the required packages

ipak <- function(pkg){
  new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
  if (length(new.pkg)) 
    install.packages(new.pkg, dependencies = TRUE)
  sapply(pkg, require, character.only = TRUE)
}

packages <- 'tidyverse'
ipak(packages)

Single file processing from within R

To isolate data between 9am and 9pm in the loaded actigraphy dataset, first run this function, to load it into the R environment. The nine_morning_to_nine_night function creates an object titled only_days in the global environment for manipulation/further analysis in R.

nine_morning_to_nine_night <- function(data = data){
 
  library(tidyverse)
  
  data$Date <- dmy(data$Date)
  data$Time <- format(strptime(data$Time, "%I:%M:%S %p"), format="%H:%M:%S")
  
  start_time <-  "09:00:00"
  end_time <- "21:00:30"
  
  only_days <<- data %>%
    filter(data$Time > start_time & data$Time < end_time)
  
  print("Variable 'only_days' has been added to your global environment, which contains only data from 9am to 9pm")
  
}

Usage

The nine_morning_to_nine_night function only requires one argument, which is the name of the object you wish to process (your loaded actigraphy dataset. This will usually be data.

nine_morning_to_nine_night(data)

Batch processing

Create a list of files you want to process

To batch process anything in R, you need to create a list of the files you wish to process, and then pass that list to R so it can perform the analysis specified. To generate this list, set your working directory to the directory where the .csv’s you want to process are located, and run the code below. The code below will print the list in the console, so make sure to eyeball it and confirm it containts the desired filenames.

Make sure that only the .csv’s you want to process are inside the file, or R will throw and error and only partially process the files inside the working directory.

# Assign all spreadsheets in wd() 
files <- Sys.glob("*.csv")
# Returns the files in the directory  
files

Run the loop

The loop will save a .csv for each individual file processed, containing only data between the time points of 9am and 9pm. The files are automatically saved to your working directory.

batch_isolate <- lapply(files, function(f) {
  
  library(tidyverse)
  
  data <- read.csv(f, header = T, sep = ",")
  
  data$Date <- dmy(data$Date)
  data$Time <- format(strptime(data$Time, "%I:%M:%S %p"), format="%H:%M:%S")
  
  start_time <-  "09:00:00"
  end_time <- "21:00:00"
  
  only_days <- data %>%
    filter(data$Time > start_time & data$Time < end_time)
  
  write.csv(only_days, paste0(f, "_9am_9pm_ISOLATED.csv"))
  
  print(paste0(f, "        has been isolated and saved as a separate .csv in your working directory"))
  
})