2

I have a readline() function in a for loop

For Simplicity let's say I have this code:

x <- character()
for (i in 1:500)  x[i] <- readline('Enter Value')

How can I automatically enter input instead of manually entering it at the console 500 times?

Jaap
  • 81,064
  • 34
  • 182
  • 193
Steve austin
  • 339
  • 2
  • 15
  • You should probably do something like `x[i] <- sample(1:10,1, replace =TRUE)` or `x[i] <- 10`. If you want to assign a value to `x[i]` calculated in the loop, assign that output to `x[i]`, e.g. `x[i] <- paste0("Loop Iteration :", i)` – Mako212 Jul 03 '18 at 18:27

2 Answers2

0

You can vectorize this command, assuming you're looking to fill the column with the same value. If that's not what you're trying to do, I'm confused as to what you want. Run my example below and say whether that's the kind of thing you're looking for

working <- iris
head(working)
working$like <- readline("Do you like this flower?  ")
head(working)
Punintended
  • 727
  • 3
  • 7
  • no this is not what I was looking for, my situation is totally different, I do not want to fill a column, I need to input the arguments of a function – Steve austin Jul 03 '18 at 18:11
  • In that case, Jaap is correct in that you're not using `readline` as intended. If there's any semblance of pattern to your arguments, generate a vector (eg, `c(rep("bongos", 10), rep("beavers", 15))`) and have your function perform different tasks depending on whether it reads `bongos` or `beavers` – Punintended Jul 03 '18 at 18:15
  • it is a bit more sophisticated than that; because I don't know what are the cases – Steve austin Jul 03 '18 at 18:19
  • If you can provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) of your data and intended format, we may be able to help with that. But saying you want to "automatically enter input" narrows it down to...well, quite a lot of entry possibilities, let alone ways to interpret those values down the line – Punintended Jul 03 '18 at 18:29
0

readline() isn't intended for automatic input. From ?readline:

Description

readline reads a line from the terminal (in interactive use).

and:

Details

The prompt string will be truncated to a maximum allowed length, normally 256 chars (but can be changed in the source code).

This can only be used in an interactive session.

Looking at ?interactive we can read the following:

An interactive R session is one in which it is assumed that there is a human operator to interact with, so for example R can prompt for corrections to incorrect input or ask what to do next or if it is OK to move to the next plot.

So, basically you are trying to use readline for something it isn't intended for.

Jaap
  • 81,064
  • 34
  • 182
  • 193