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.
Related
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!
Write a function h1 which uses a for-loop and the explicit formulation
h(x, n) = 1 + x + x2 + ...xn = ∑xn
Code:
h2 <- function(x,n){
i <- 1
out=0
for (i in seq(from=0,to=n)) {
out = out + x^i
}
}
I have tried this but this doesnt seem to work? Is there an alternative way to find the for and while loop for this problem
A function returns the result of the last statement in its body which in this case is for but for always returns NULL. (The line after the for is regarded as part of the for so it is not regarded as the last line.)
res <- for(i in 1:3) i
res
## NULL
Make sure that out is the last statement run. That is add this
out
as the last line in the body just before the final }.
Note that this one-linear would also work:
sum(x^(0:n))
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.
I've got a problem with output from S3 function. I try to overload "+" function to act with two vectors like with polynomial parameters. It's my university project. Code is below:
'+.ply' <- function(a,b){
size <- max(length(a$polynomial),length(b$polynomial))
size
aAdd <- a$polynomial
bAdd <- b$polynomial
if (length(aAdd) == size) {
aAdd = aAdd
} else {
length(aAdd) <- size
}
aAdd[is.na(aAdd)] <- 0
if (length(bAdd) == size) {
bAdd = bAdd
} else {
length(bAdd) <- size
}
bAdd[is.na(bAdd)] <- 0
cat("Polynomial of degree ", paste(length(aAdd+bAdd)-1),
" with coefficients ", paste(aAdd+bAdd))
}
Code is working fine, but in return it gives me output
*Polynomial of degree 3 with coefficients 3 4 6 3NULL*
I need to use cat in order to avoid [1] index which occurs while I'm using print, paste combo. I know that there are plenty threads about this problem, but I can't find any sollution for such problem during function overloading. I will be thankful for help.
I am working on a poker deck prability simulation. I would like to get the probability that player 1 is dealt a hand consisting of a single suit only.
I got the code below, however, I get the following error:
> checkDeck1()
Error in unique(deck[1:4]) : argument "deck" is missing, with no default
Code:
pokerdeck <- rep(LETTERS[1:4],13)
deck <- sample(x=pokerdeck, size=13) #Deck of player 1!
checkDeck1 <- function(deck) {
uniquedeck <- unique(deck[1:13])
## if it is only a single suit
if (length(uniquedeck)==1) {
rv <- TRUE
} else {
rv <- FALSE
}
return (rv)
}
checkDeck1()
You want to call
checkDeck1(deck)
In the code of your function checkDeck1, the scope of the variable deck is local - the fact that you name this variable like a global variable locally overwrites it.