files and directories
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(message = FALSE)
http://theautomatic.net/2018/07/11/manipulate-files-r/
https://astrostatistics.psu.edu/su07/R/html/base/html/files.html
get and change working dir
getwd()
setwd("/path/to/wd/")
using “here” package
library(here)
here::here()
here::set_here()
check if files, dirs exists
file.exists("test.txt") # [1] FALSE
dir.exists("test_dir") # [1] TRUE
create files, dirs
dir.create("test_dir")
file.create(file.path("test_dir", "test.txt"), overwrite = TRUE)
file.create(file.path("test_dir", "test.csv"))
# create a whole bunch of files
file.path("test_dir", paste0("file", 1:5, ".txt"))
sapply(file.path("test_dir", paste0("file", 1:5, ".txt")), file.create)
edit file
file.edit(file.path("test_dir", "test.txt"))
delete files
file.remove(file.path("test_dir", "test.txt"))
dir.create(file.path("test_dir", "to_be_removed"))
unlink(file.path("test_dir", "to_be_removed"), recursive = TRUE)
copy files, dirs
dir.create(file.path("test_dir", "inner_dir"))
file.copy(file.path("test_dir", "test.txt"), file.path("test_dir", "inner_dir"), overwrite = TRUE)
symlink
file.symlink(from, to)
list files in dir
list.files(file.path("test_dir"))
list.files(file.path("test_dir"), recursive = TRUE) # lists files in inner_dir
list.files(file.path("test_dir"), recursive = TRUE, full.names = TRUE) # get full path, starting from current dir
# use pattern to subset list.files() results
list.files(file.path("test_dir"), pattern = ".csv")
get file info
file.info(file.path("test_dir", "test.txt"))
# size isdir mode mtime ctime atime uid gid uname grname
# test_dir/test.txt 0 FALSE 644 2020-05-04 17:46:56 2020-05-04 17:46:56 2020-05-04 17:52:52 501 20 minghan staff
file.mtime(file.path("test_dir", "test.txt")) # [1] "2020-05-04 17:46:56 EDT"
# file.ctime(file.path("test_dir", "test.txt")) # no such function...
file.info(file.path("test_dir", "test.txt"))$ctime # [1] "2020-05-04 17:46:56 EDT"
get file basename
basename(file.path("test_dir", "test.csv"))
get dir name of a file
dirname(file.path("test_dir", "test.csv"))
get file extension
library(tools)
file_ext(file.path("test_dir", "test.csv"))
open a GUI window to select file
# file.choose()
move a file
# install.packages("filesstrings")
library(filesstrings)
file.move(file.path("test_dir", "file1.txt"), file.path("test_dir", "inner_dir"))