Read from console in R

To read from console some user input we can use the following:

ask <- function() {
    cat( "You will be asked for some values" )
    return( scan( n = 1 ) )
}

This lines generate the following behaviour:

R> value.1 <- ask()
You will be asked for some values
1: 7
Read 1 item

So when we shoe the content of value.1:

R> print( value.1 )
[1] 7

We can do the same asking for more values:

ask <- function( N = 1 ) {
    cat( "You will be asked for some values" )
    return( scan( n = N ) )
}

Getting a similar behaviour:

R> value.5 <- ask( N = 5 )
You will be asked for some values
1: 5
2: 4
3: 3
4: 2
5: 1
Read 5 items

And, of course, getting a similar result:

R> print( value.5 )
[1] 5 4 3 2 1

But, what happens if we type some other input different than numbers:

R> value.c <- ask()
You will be asked for some values
1: A
1: B
Error en scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  : 
  scan() esperaba 'a real', obtuvo 'A'

This can be solve adding a new argument:

R> ask <- function( N = 1, type = double() ) {
    cat( "You will be asked for some values" )
    return( scan( n = N, what = type ) )
}

And be used as:

R> value.c <- ask( type = character() )
You will be asked for some values
1: A
Read 1 item

So we can get the character:

R> print( value.c )
[1] "A"
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: