Create User-Manipulable Inputs

47 views Asked by At

I've written a code and trying to create user-editable values so that another user who is not acquainted with coding, may change the variables they want without having to read and understand the code.

I would like the following examples to work:

#Name of file here:
  file <- "mydata.csv"
#Select columns desired:
  offsets <- "-50,-25,0,25,50"
  
setwd("~/R/projects")
df <- read.delim("~/R/projects/file", sep=",", header=FALSE)

keep <- c(offsets)

These are just two of many examples so I would really appreciate some pointers on how to achieve this.

Here are some of the outputs:

> offsets <- -50,-25,0,25,50
Error: unexpected ',' in "offsets <- -50,"
> 
> keep <- c(offsets)
Error: object 'offsets' not found
>
> offsets <- '-50','-25','0','25','50'
Error: unexpected ',' in "offsets <- '-50',"
> 
> keep <- c(offsets)
Error: object 'offsets' not found
>
> offsets <- "-20,-10,0,10,20"
> keep <- c(offsets)
> 
> str(keep)
 chr "-20,-10,0,10,20"

The original line that works is:

> keep <- c(-50, -25, 0 , 25, 50)
> keep
[1] -50 -25   0  25  50
2

There are 2 answers

0
MrFlick On BEST ANSWER

Since R is a programming language, it has very particular rules for how input must be formatted for the R interpreter to run. If you want to be more tolerant for different types of input, it's often better to accept a string/charcter value and then parse it yourself into the format that R needs. So if you accept a string of number separated by commas,

offsets <- "-50,-25,0,25,50"

you can parse that with something like:

offsets <- as.numeric(strsplit(offsets, ",")[[1]])
0
M Aurélio On

If it is on Windows you could use winDialogString

#Name of file here:
file <- winDialogString("Name of file here:", "mydata.csv")

#Select columns desired:
offsets <- 
  winDialogString("Select columns desired by indices: (eg: -50,-25,0,25,50)", "-50,-25,0,25,50") |>
  strsplit(",") |>
  unlist() |>
  as.numeric()

winDialogString returns a character vector of length 1, so you have to transform it before use and you also have to put conditions check to know that the code will work properly