[R] Help with if else branching print out

Eric Berger ericjberger @ending from gm@il@com
Tue Dec 18 10:09:58 CET 2018


I often use sprintf() to control formatting of text strings. e.g.

sprintf("%s is not between 1 or 15\n",nums)

See ?sprintf for details

HTH,
Eric


On Tue, Dec 18, 2018 at 10:56 AM Andrew <phaedrusv using gmail.com> wrote:

> Hi all
>
> Playing around with some branching using if, if else, and else, I wrote
> the following very basic script:
>
>
> [code block]
>
> ## Take single value input from user:
> # Note 'as.integer' to convert character vector to numeric for testing
>
> nums <- (as.numeric(readline("Please enter a number between 1 and 15: ")))
>
> ## Truth test routine:
> # Set conditional values and test input against conditions and then
> print outcome
>
> if ((nums > 15) || (nums < 1))
> {
>    print(c(nums, "is not between 1 or 15"))
> } else if ((nums > 5) && (nums < 10) || (nums == 12))
> {
>    print(c(nums, "falls within 6 - 9 inclusively, or is 12"))
> }  else
> {
>    print( c(nums, "is *not* 6 - 9 inclusive, nor is it 12"))
> }
>
> [/ code block]
>
>
> However, it prints out like this:
>
> [output]
>
> Please enter a number between 1 and 15: 17
> [1] "17"                     "is not between 1 or 15"
>
> Please enter a number between 1 and 15: 9
> [1] "9"
> [2] "falls within 6 - 9 inclusively, or is 12"
>
> Please enter a number between 1 and 15: 13
> [1] "13"                                     "is *not* 6 - 9 inclusive,
> nor is it 12"
>
> [/ output]
>
>
> How do I:
>
> (a) reduce the gap between the reported number (i.e., 17, 9, 13) in each
> of the lines? and
>
> (b) ensure that in the case of the second run using 9 as the input, the
> print is not over two lines?
>
> I will try the switches function soon, which may yield a different
> output format, but wanted to get my head around why this is printing out
> the way it is.
>
> Many thanks for any help.
>
> Andrew
>
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list