use scan() function in R to extract value from console - r

I am trying to extract an integer value from R console by asking the user the question: "How many dice do you want to save?". The user can only choose a number between 1 to 5.
Following is my code snippet:
# .... previous steps to roll 5 dices and print output
cat("Player ", player_start, ":\nDice after 1 roll(s):\n", x, "\nHow many dice do you want to save?")
number_saved_dices <- scan()
#if number_saved_dices out of the range, stop the function
if(number_saved_dices > 5 || number_saved_dices < 0 ) {
stop("You can only save between 0 and 5 dices. Try again:")
} else if(number_saved_dices == 5 ) {
#if player wants to save all five
print("For which category should the result be used?")
} else if( 0< number_saved_dices < 5 ) {
print("Please enter the values of the dice to save.")
}
For example, if the user wants to save 12 dices, then the script should be stopped with the error message "You can only save between 0 and 5 dices. Try again. " However, I can't perform if-else control flow with the number_saved_dices.
I would appreciate any help or insight!!
Thanks very much in advance!

Related

Gravityform easy calculation - but total is not beginning from 0

I have a pretty simple calculation in gravityform, but because I add +1 and +0.5 to what people are filling out in the input fields, then the total from the begining is showing a number instead of only 0.
Example:
Field A +1
Field B +0.5
Calculation Field A x B x 295. But because I add +1 and +0.5 to what people put in the input field, then the total from the beginning, shows 147,5. Because it calculate 1*.0.5*295 = 147,5.
But I want the total just to show 0 until people are filling out the input field.
How can I avoid this?
Your best bet for a code-based solution will probably be to use the gform_calculation_result filter and check a value of 1 or 0.5 and return 0 instead.
gform.addFilter( 'gform_calculation_result', function( result, formulaField, formId, calcObj ) {
if ( result == 1 || result == 0.5 ) {
result = 0;
}
return result;
} );
An alternate approach would be to use conditional statements right in the calculation formula, powered by our Gravity Forms Advanced Calculations plugin.
You could check if the field has a value and provide a formula for that and return 0 otherwise.
if ( F1 > 0 ):
F1 + 1
else:
0
endif;

Recursion error in R (Fibonacci sequence)

So I am trying to learn R on my own and am just working through the online tutorial. I am trying to code a recursive function that prints the first n terms of the Fibonacci sequence and can't get the code to run without the error:
Error in if (nterms <= 0) { : missing value where TRUE/FALSE needed
My code does ask me for input before entering the if else statement either which I think is odd as well. Below is my code any help is appreciated.
#Define the fibonacci sequence
recurse_fibonacci <- function(n) {
# Define the initial two values of the sequence
if (n <= 1){
return(n)
} else {
# define the rest of the terms of the sequence using recursion
return(recurse_fibonacci(n-1) + recurse_fibonacci(n-2))
}
}
#Take input from the user
nterms = as.integer(readline(prompt="How many terms? "))
# check to see if the number of terms entered is valid
if(nterms <= 0) {
print("please enter a positive integer")
} else {
# This part actually calculates and displays the first n terms of the sequence
print("Fibonacci Sequence: ")
for(i in 0:(nterms - 1)){
print(recurse_fibonacci(i))
}
}
This is a problem of readline in non-interactive mode. readline does not wait for a keypress and immediately executes the next instruction. The solution below is the solution posted in this other SO post.
I post below a complete answer, with the Fibonnaci numbers function a bit modified.
recurse_fibonacci <- function(n) {
# Define the initial two values of the sequence
if (n <= 1){
n
} else{
# define the rest of the terms of the sequence using recursion
Recall(n - 1) + Recall(n - 2)
}
}
#Take input from the user
cat("How many terms?\n")
repeat{
nterms <- scan("stdin", what = character(), n = 1)
if(nchar(nterms) > 0) break
}
nterms <- as.integer(nterms)
# check to see if the number of terms entered is valid
if(nterms <= 0) {
print("please enter a positive integer")
} else {
# This part actually calculates and displays the first n terms of the sequence
print("Fibonacci Sequence: ")
for(i in 0:(nterms - 1)){
print(recurse_fibonacci(i))
}
}
This code is the contents of file fib.R. Running in a Ubuntu 20.04 terminal gives
rui#rui:~$ Rscript fib.R
How many terms?
8
Read 1 item
[1] "Fibonacci Sequence: "
[1] 0
[1] 1
[1] 1
[1] 2
[1] 3
[1] 5
[1] 8
[1] 13
rui#rui:~$
To make it work with Rscript replace
nterms = as.integer(readline(prompt="How many terms? "))
with
cat ("How many terms?")
nterms = as.integer (readLines ("stdin", n = 1))
Then you can run it as Rscript fib.R, assuming that the code is in the file fib.R in the current working directory.
Otherwise, execute it with source ("fib.R") within an R shell.
Rscript does not operate in interactive mode and does not expect any input from the terminal. Check what interactive () returns in both the cases. Rscript will return FALSE as it is non-interactive, but the same function when run within an R shell (with source ()) it will be true.
?readline mentions that it cannot be used in non-interactive mode. Whereas readLines explicitely connect to stdin.
The code works fine but you shouldn't enter it into the terminal as is. My suggestion: put the code into a script file (ending .R) and source it (get help about it with ?source but it's actually pretty straightforward).
In R-Studio you can simply hit the source button.

When running code in R was given an error that there was a missing value where true/false needed and I can't fix it

I am new to using R and have minimal amount of Python experience. I am sure this is an easy fix but I am just not seeing it. I was given a code to run a Fibonacci sequence to 100 and I copy and pasted it, but I am getting the following error code: Error in if (numterms <= 0) { : missing value where TRUE/FALSE needed. I know this has to do with the if/else clause but I am not seeing the problem.
I have run through the code a couple different ways but it has not helped. And the person to assist is not available during the weekend. Any help would be appreciated.
# take the max number input from the user
numterms = as.integer(readline(prompt="What is your max number? "))
# first two items
num1 = 0
num2 = 1
counter = 2
# check if the number of terms is valid
if(numterms <= 0) {
print("Please enter an integer above zero")
} else {
if(numterms == 1) {
print("The Fibonacci sequence:")
print(num1)
} else {
print("The Fibonacci sequence:")
print(num1)
print(num2)
while(counter < numterms) {
numth = num1 + num2
print(numth)
# update values
num1 = num2
num2 = numth
counter = counter + 1
}
}
}
If you just execute the code numterms is not correctly defined. It is normally defined by a user input: The function readline reads the numbers the user types in the command line. If you just execute this line you can properly define numterms.
If you execute all the code at once numterms is set to NA which cannot be compared to 0 in the numterms <= 0 clause. In this case numterms <= 0 is also NA which is not a logical value and can therefore not be evaluated by if. This ultimately causes your error.
The solution would be to just run the first line of your code and enter the number and only after you entered the number to execute the rest of the code.
Alternatively you can define your code as a function:
printFibonacci <- function(){
numterms = as.integer(readline(prompt="What is your max number? "))
if(is.na(numterms)){
numterms <- 4
}
# first two items
num1 = 0
num2 = 1
counter = 2
# check if the number of terms is valid
if(numterms <= 0) {
print("Please enter an integer above zero")
} else {
if(numterms == 1) {
print("The Fibonacci sequence:")
print(num1)
} else {
print("The Fibonacci sequence:")
print(num1)
print(num2)
while(counter < numterms) {
numth = num1 + num2
print(numth)
# update values
num1 = num2
num2 = numth
counter = counter + 1
}
}
}
}
And then just call your function with printFibonacci(). In this case the prompt and answer of the readline function gets executed first and numterms can be defined by the user before the rest of the code is executed.

Variable outside function is reset every time during recursion

I am a beginner at R, so please pardon me if there is a key programming construct about R that I am not understanding.
I have the following code:
tab_level <- 0
print_tree <- function (node_index) {
cat (tab_level)
cat ("\n")
# Past the tree domain
if (node_index >= 2^depth ) {
tab_level <- tab_level - 1
cat ("\n")
return()
}
# Print the value in the node
# Tabs
#cat(node_index)
for (i in 0:tab_level) {
cat("\t")
}
tab_level <- tab_level + 1
print_tree(2*node_index)
print_tree(2*node_index + 1)
}
print_tree (1)
However, when I do this and read the cat outputs, tab_level is 0 every single time, in the output. Am I understanding R incorrectly, and how it works with variable scope? I come from a Java background, if that helps at all, and I'm assuming it works similarly to Java.

nested if statment in R

I'm trying to implement following thing in R, but I'm new in R and my code doesn't work.
I have matrix A, I did coordinates changes .
I want to write two function:
1) give the element of matrix, given coordinates
2) give the coordinates given number.
the pseudo code is right, the only problem is my syntax. can somebody correct it ?
f<- as.numeric(readline(prompt="Please enter 10 to get coordinate of number,and 20 to get the number > "));
if(p==10){
# give the number, given coordinates
i<- as.numeric(readline(prompt="Pleae enter i cordinate > "));
j<- as.numeric(readline(prompt="Pleae enter j cordinate > "));
if (i>0&j<0) return A[5+i,5+j]
if (i>0&j>0) return A[5+i,5+j]
if (i<0&j>0) return A[5+i,5-j]
if (i<0&j<0) return A[5+i,5-j]
}else if (p==20){
#give the cordinate, given number
coordinate <- which(A==number)
[i,j]<-A[2-coordinate[0],coordinate[1]-2]
}
}
Warning: what if i or j is equal to zero? Next, make a single variable which is the decimal representation of binary i,j, That is,
if(p==10){
x <- (i>0) + 2*(j>0) +1
# x takes on values 1 thru 5. This is because switch requires nonnegative integer
switch(x,
return A[5+i,5+j],
return A[5+i,5+j],
return A[5+i,5+j],
return A[5+i,5+j]) # change the +/- indices as desired
}else{
#etc.
And, finally, you should make this a function, not a collection of commands.
Edit - I skipped this before, but: you cannot call an index of 0 so you need to fix a number of things in the line [i,j]<-A[2-coordinate[0],coordinate[1]-2]
The syntax is as follows:
x <- 4
if (x == 1 | x == 2) print("YES")

Resources