HI, I am rather new to R. I have written code in the past and my script works when I don't add the user input.I have 14 files in each of 2 txt file paths that have to be selected from. Each are specifically paired. the DS01 is paired with VDS1_1. I see the file path in the environment widow and it lists the files successfully. When I run it, I get no errors. But when I type in the DS01 in the interactive mode, I get the
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") : cannot open file 'DS1': No such file or directory
The interactive code is
Before I had made it interactive, it was working exactly as it was suppose to performing dyplr mutate and ggplot2 operations. So it has to be something I am doing in the if then else statements . Also I am not married to this code. If someone has a way to make it so that askUser it can just use the numerical value in lapply or what have you I will use it. I just have had no success using lapply.
Thank you. I had been leaning in that direction after some investigation, but was still unsure. But now it works. I also want to know if there is a better way to right my if-then-else or an "apply" that can be used for calling the user defined input. I don't want to write 14 ifelses. They are in numerical order and I have removed all spaces.
You could put the list of filenames into a dataframe and then do a lookup on the dataframe.
Or if they all have the same form, you could use string manipulation (e.g. with stringr) to parse the user input and construct the appropriate filename.
Something like this:
library(stringr)
askUser <- readline(prompt="Please, enter the data set (1-14) using DS# format: ")
# askUser <- "DS01"
x <- str_extract(askUser, "(?<=DS)[0-9]+") # extract the number
if (!is.na(x)){ # check there's a number
SCfilename <- str_replace("E:/Updated_Datasets_20190603/DS_textfiles/DS##.txt", "(?<=DS)##", x)
SC120000 <- read.delim(file=SCfilename, header = TRUE)
VDSfilename <- str_replace("E:/Updated_Datasets_20190603/VDS/VDS_DS#_1.txt", "(?<=DS)#", as.character(as.numeric(x)))
VDS <- read.delim(file=VDSfilename, header=TRUE)
}
Edited:Well, I am not sure what is going on. But when I run the script the x comes back as NA_character
and the files do not load. I have not changed anything.