Creating a Prompt/Answer System to Input Data into R

Creating a Prompt/Answer system to input data into R

Since this is supposed to be used as interactive code only, readline() can work for you. I did not add any error checking, but you'd probably want to do a fair amount of that to ensure proper input. Here's the core concept though:

fun <- function(){
x <- readline("What is the value of x?")
y <- readline("What is the value of y?")
t <- readline("What are the T values?")
v <- readline("What are the V values?")

x <- as.numeric(unlist(strsplit(x, ",")))
y <- as.numeric(unlist(strsplit(y, ",")))
t <- as.numeric(unlist(strsplit(t, ",")))
v <- as.numeric(unlist(strsplit(v, ",")))

out1 <- x + y
out2 <- t + v

return(list(out1, out2))

}

Using variable input for system()

I rather do this in C:

#include <stdio.h>
#include <stdlib.h>
int sumUp(int x, int y, int z, int *sum);

int main()
{
int x1,x2,x3;
int total = 0;
x1 = strtol(argv[1], NULL, 10);
x2 = strtol(argv[2], NULL, 10);
x3 = strtol(argv[3], NULL, 10);

sumUp(x1,x2,x3,&total);
printf("Your total is :%d\n", total);

system("pause");

}

int sumUp(int x, int y, int z, int *sum)
{
*sum = x + y + z;
}

And this in R:

x <- 0
y <- 0
z <- 0

readint <-function(){
a <- readline(prompt = "Enter a number: \n")
}

x <- as.numeric(readint())
y <- as.numeric(readint())
z <- as.numeric(readint())
cmd <- paste("Practice.exe", x, y, z)
system(cmd, intern = TRUE)

R: how do I prompt the user for input from the console?

Readline does wait for the user's input. But the problem is that, in your case, when you run all of your code at once, R will treat 'n2<-readline(prompt="Enter skip 2: " )' as the user's input (it indeed is) to the first readline. This is the root of the problem.

So basically you have two choices to deal with your problem, the first is to find some specific package in R that halts R execution process when prompting; the second one is to stick to the R base, but only use readline in the ending block of your file. In your case, you can use a little trick like this:

{
n1<-readline(prompt="Enter skip 1: " )
n2<-readline(prompt="Enter skip 2: " )
n1<-as.integer(n1)
n2<-as.integer(n2)
}

The rationale behind this trick is this: when R read the thing between { and }, it will treat all of the things in between as a whole command, this is the ending block of the code, so it behaves like what you want. R will not feed part of this command to another part of the command, thus prevents the problem you met.

You can develop similar tricks yourself, like putting the readline in a function:

foo <- function(){
n1<-readline(prompt="Enter skip 1: " )
n2<-readline(prompt="Enter skip 2: " )
n1<-as.integer(n1)
n2<-as.integer(n2)
c(n1, n2)
}

foo()

In this case, the whole foo function will act as the ending block of your code, and all things work as you want. Hope this helps.

Combining data based on user input in R

assign called within a function by default does the assignment in the function's environment, instead of in the global environment. So basically, it's like storing the result in a variable within the function. Once the function returns, that value is lost. The following illustrates this (this is essentially what you are doing):

fxn <- function() assign("xyz", 1)
fxn()
print(xyz)
# Error in print(xyz) : object 'xyz' not found

If you want to use assign to store in the global environment (outside of the function), you could add argument envir = .GlobalEnv to your call to assign.

fxn <- function() assign("xyz", 1, envir = .GlobalEnv)
fxn()
print(xyz)
# [1] 1

That being said, using assign to store values is often not the preferred way to store data in R (you can read more about that at Why is using assign bad?). You might find it easier to maintain your code if you stored it in a list. As an example, if you had an initial list l <- list(), then you could store your new data in that list with l[[Site]] <- rbindlist(mget(apropos(Site), inherits = TRUE) and access it with [[ or $.

Add 'y to confirm' confirmation dialogue to an R function?

Why not a simple readline function to get input from the user?

checkFunction <- function() {
user_input <- readline("Are you sure you want to run this? (y/n) ")
if(user_input != 'y') stop('Exiting since you did not press y')
print('Do something')
}

checkFunction()
#Are you sure you want to run this? (y/n) y
#[1] "Do something"

checkFunction()
#Are you sure you want to run this? (y/n) n
#Error in checkFunction() : Exiting since you did not press y

Update column by prompting user input R

First make a function...

checkRow<-function(df){
match<-vector()
for(i in 1:nrow(df)){
print(df[i,])
ans<-readline("Is this a match? (y or n)")
match<-c(match, ans)
}
return(cbind(df, match))
}

Then call it as such:

checked<-checkRow(df)

taking inputs through pop up window in R

The svDialogs provides such solution.

library(svDialogs)
user.input <- dlgInput("Enter a number", Sys.info()["user"])$res

which gives a pop-up as

snap1

Also, user input is stores

> user.input
[1] "68"

How to get a user input in command prompt and pass it to R

From the documentation of readline():

This can only be used in an interactive session. [...] In non-interactive use the result is as if the response was RETURN and the value is "".

For non-interactive use - when calling R from the command line - I think you've got two options:

  1. Use readLines(con = "stdin", n = 1) to read user input from the terminal.
  2. Use commandArgs(trailingOnly = TRUE) to supply the input as an argument from the command line when calling the script instead.

Under is more information.

1. Using readLines()

readLines() looks very similar to readline() which you're using, but is meant to read files line by line. If we instead of a file points it to the standard input (con = "stdin") it will read user input from the terminal. We set n = 1 so that it stops reading from the command line when you press Enter (that is, it only read one line).

Example

Use readLines() in a R-script:

# some-r-file.R

# This is our prompt, since readLines doesn't provide one
cat("Please write something: ")
args <- readLines(con = "stdin", n = 1)

writeLines(args[[1]], "output.txt")

Call the script:

Rscript.exe "some-r-file.R"

It will now ask you for your input. Here is a screen capture from PowerShell, where I supplied "Any text!".

Print screen from PowerShell

Then the output.txt will contain:

Any text!


2. UsingcommandArgs()

When calling an Rscript.exe from the terminal, you can add extra arguments. With commandArgs() you can capture these arguments and use them in your code.

Example:

Use commandArgs() in a R-script:

# some-r-file.R
args <- commandArgs(trailingOnly = TRUE)

writeLines(args[[1]], "output.txt")

Call the script:

Rscript.exe "some-r-file.R" "Any text!"

Then the output.txt will contain:

Any text!

User input in R

cat("input x: ")
x <- readLines(con="stdin", 1)
cat(x, "\n")


Related Topics



Leave a reply



Submit