Home > front end >  Define function's argument in terminal by user in R
Define function's argument in terminal by user in R

Time:04-20

I have a function with single argument

define <- function(x) {...}

now I want to use readline function to let user define this argument itself in terminal I tried the following code but it does not work:

data <- define(readline(prompt = "Please enter Code: "))

CodePudding user response:

I defined a simple function:

define <- function(x) {
  y = as.numeric(x)   1
  return(y)
}

When you ask the user to set a value for example 3, the output looks like this:

data <- define(readline(prompt = "Please enter Code: "))
data

Please enter Code: 3
> data
[1] 4

As you can see, the code does its job.

Edit for you comment:

You can add a menu to give user a choice like this:

define <- function(x) {
  choice <- menu(c("Tc","Tr","Ty","Mn"))
  return(choice)
}

data <- define(readline(prompt = "Please enter corresponding number: "))

Which looks like this:

> data <- define(readline(prompt = "Please enter corresponding number: "))

1: Tc
2: Tr
3: Ty
4: Mn

Selection: Tc
> data
[1] 1

CodePudding user response:

define <- function(x) {
data <- define(readline(prompt = "Please enter Code: "))
data <- as.numeric(unlist(strsplit(data, ",")))
return(data)

}

Is it something like this you want?

  • Related