Individual command working, but not within a script!

Hello,
I am quite puzzled with what follows, and can't find a solution yet... I hope to have better luck here!

IF I run the following commands on a single line, one at a time, within R-Studio (or R console), everything works fine:

n=as.integer(readline(prompt='Enter Sample Size (n): '))
Enter Sample Size (n): 56

N_Sample=as.integer(readline(prompt='Enter the number of sample to draw (k): '))
Enter the number of sample to draw (k): 1000
N_Sample
[1] 1000

But when these lines are made parts of a script, I would expect a prompt for each items. But instead, it looks like the second prompt becomes the answer to the first! :

n=as.integer(readline(prompt='Enter Sample Size (n): '))
Enter Sample Size (n): N_Sample=as.integer(readline(prompt='Enter the number of sample to draw (k): '))
Warning message:
NAs introduced by coercion

I am sure this is a result of my inadequate knowledge of R programming, but can anybody tell me what I am missing here?

Thanks for any help...

Yep! That solves the problem! THANKS!

Oupppsss... Too fast! It worked piece by piece, but once in a script:

Script:
cat("Enter Sample Size (n):")
n = as.integer(x = readLines(con = stdin(),ok=TRUE, n = 1))

cat("Enter the number of sample to draw (k):")
N_Sample = as.integer(x = readLines(con = stdin(),ok=TRUE, n = 1))

print(sample.int(n,N_Sample))

Output:

cat("Enter Sample Size (n):")
Enter Sample Size (n):> n = as.integer(x = readLines(con = stdin(),ok=TRUE, n = 1))

cat("Enter the number of sample to draw (k):")
Enter the number of sample to draw (k):> N_Sample = as.integer(x = readLines(con = stdin(),ok=TRUE, n = 1))

Looks like the data input command (readLines) gets the next line as data!

print(sample.int(n,N_Sample))
Error in if (useHash) .Internal(sample2(n, size)) else .Internal(sample(n, :
missing value where TRUE/FALSE needed

how are you choosing to execute the script ?
I recommend you source it
source("myscriptname.R")

Thanks. I will check how it would go that way. At this time, I got around the problem by reorganizing the whole process into 3 functions where no input is required. I would like to know why a simple data input could fail the way it does... But I got what I need with cleaner syntax:

SampleAnalysis(SampDistr(RandPop(3,10000,3.4),2000,20))

I am quite new to R programming, and have a whole world to explore/learn!

Thanks again for the tip.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.