0

I run into issues reading in csv files with dynamic names and avoiding hard coding the file path. I'd like short tidy code (non-hardcoded). If I hardcode the full path (everything before the "~") it reads in the files fine. But soft-coding (if that is the opposite of hard coding) the file path it gives the error (despite showing the correct path in the error. I have two variable parts of the file name that I paste into the file name before reading it in. If I avoid paste and just type a path per individual it also works.

#dynamic part I usually have in a loop with all the options. 
part_a <- "outside" #other options here in my loop include "inside"
part_b <- "late" # other option "early" or "preterm"

#reading in the df
df <-read.csv(paste0("~/Data/FromR/clean_",part_a,part_b,"_2016.csv"),
                           check.names=FALSE, na.strings="null")

Error in file(file, "rt") : cannot open the connection
    In addition: Warning message:
    In file(file, "rt") :
      cannot open file 'C:/Users/myname/Documents/Data/FromR/clean_outsidelate_2016.csv': No such file or directory

if I use getwd() in the first part of the paste in place of ~ as suggested here it works by producing this string "C:/Users/myname/Documents/MyR_Projects/Specific_R_project/" at the beginning of the paste. But how can I get it to work with the "~"? when using the ~ it stops at the "Documents" folder...

The desired outcome is to read in the file without error perform functions and repeat with other files. My loop works fine hardcoded, and I only wanted to make it more general or softcoded.

andemexoax
  • 323
  • 3
  • 15

1 Answers1

0

I just tried to read a file (testFile.txt) in my home from a different wdand it works fine with ~

 myFile <- "testFile
 mymy <- ".txt"
 ciao <- read.delim(paste0("~/",myFile,mymy))

In powershell you can use %~% (have a look here tread), but I am not sure how to expand the $HOME in R.

#-------- edit

Have a look here and here. Basically any variable defined in your .Renviron should be accessible.

fra
  • 832
  • 6
  • 14
  • Fixed my question to have correct file name. What resources are there for checking how a single character symbols are treated such as `~`? – andemexoax Oct 02 '19 at 00:55