Q:

R: strange unwanted output from readline

I am trying to get input from stdin in R. 
here is my code
fil <- file("stdin")
open(fil)
fn <- readline(fil)
fn <- strsplit(fn, split = ' ')
f <- fn[[1]][1]
n <- fn[[1]][2]
write(n, stdout())
close(fil)

when I run this code
> fil <- fil("stdin")
> open(fil)
> fn <- readline(fil)
4

I get this unnecessary number 4 out of nowhere. sometimes it's 3 sometimes its 4. where is it coming from?

A:

readline() is supposed to get input from the user in interactive mode. The argument of readline is a prompt:
> n = readline("enter num: ")
enter num: 3
> n
[1] "3"

The line
fn <- readline(fil)

is interpreting fil as a prompt. The number that you are seeing (3 or 4) is thus the file handle assigned to stdin by the open() function, which makes for a pretty cryptic prompt.
I think that (assuming that you are trying to pipe in data from stdin in a batch setting) you need to use readlines() instead. Type ?readlines for information. On the other hand, if you are writing a program to get input interactively from the keyboard, skip that part about opening stdin as a file and just use readline(<prompt of your choice>). The function readline() is already hooked up with stdin.

