Evaluating the output of a condition in R? - r

In the below R function, I was wondering how I could get R to evaluate whether the object input outputs n or es?
Note: I will need to know the exact output of input, so I canNOT be using identical() etc.
Here is what I have tried with no success:
d = function(n, es){
input = if(length(n) > 1) n else if(length(es) > 1) es else n
if(input == n) cat("yes") else cat("No") # IF `input` is `n` cat("yes") otherwise cat("no")
}
d(n = c(2, 3), es = 1)

try to use if(identical(n, input)) cat("yes") else cat("No"). == cannot be

Related

curve() using a function with argument in R

ppt=function(v, tail = 0.5){
if (tail == 1){
6/pi^2/v^2
} else {
if (v < 11) {
(1-tail)*(11-v)/55
} else {tail*6/pi^2/(v-10)^2}
}
}
curve(ppt(tail = 0.2))
Error in curve(ppt(tail = 0.2)) :
'expr' must be a function, or a call or an expression containing 'x'
How should I plot a smooth curve for the function ppt() with different values of variable tail?
Thank you.
Either (1) rewrite ppt to vectorize it (not shown) or else (2) use Vectorize as shown below in which case ppt does not have to be modified. Also use this syntax.
curve(Vectorize(ppt)(x, tail = 0.2), ylab = "ppt")
Maybe the following trick?
w = 0.2
g <- function(z) ppt(z, tail = w)
curve(g)
And do not forget to replace, as #MrFlick points out in the comment:
if (v < 11) {
(1-tail)*(11-v)/55
} else {tail*6/pi^2/(v-10)^2}
by
ifelse(v < 11, (1-tail)*(11-v)/55, tail*6/pi^2/(v-10)^2)

replacement has length zero in fibonacci sequence in R code

So I have this code for the fibonacci sequence, and I keep getting an error when I try to print out the value of the function.
fibonacci <- function(nn) {
if (!(nn%%1==0) | (nn<1)){
return(0)
}
my.fib <- c(1,1)
for (kk in 3:nn){
my.fib[kk] <- my.fib[kk-1] + my.fib[kk-2]
}
return(my.fib[nn])
}
fibonacci(7)
fibonacci(5)
fibonacci(1)
fibonacci(1.5)
fibonacci(0)
It prints everything correctly for 7,5,1.5 and 0, as it gives me the vaules 13, 5, 0, and 0. But when trying to print fibonacci(1), I get the error
Error in my.fib[kk] <- my.fib[kk - 1] + my.fib[kk - 2] :
replacement has length zero
I want to leave as much as the code the same as possible.
Add another if condition to check for nn = 1.
fibonacci <- function(nn) {
if (!(nn%%1==0) | (nn<1)){
return(0)
} else if(nn == 1) return(1)
my.fib <- c(1,1)
for (kk in 3:nn){
my.fib[kk] <- my.fib[kk-1] + my.fib[kk-2]
}
return(my.fib[nn])
}

R: How to use current function output's within this function

I write a R function using if & else if in it. See the code below:
i_ti_12 <- function(x){
if (x <= 44)
{ti = exp(-13.2238 + 0.152568*x)}
else if (x >= 49)
{ti = -0.01245109 + 0.000315605*x}
else (x > 44 & x < 49)
{ti = (x-44)*(i_ti_12(49))/(49-44) + (49-x)*(i_ti_12(44))/(49-44)}
return(ti)
}
I want to use this function's output, i_ti_12(49) within this function, but the above code doesn't work. The output is:
> i_ti_12(49)
Error: C stack usage 7974292 is too close to the limit
The simple solution is just replace i_ti_12(49) by -0.01245109 + 0.000315605*49, but its not a clear way to solve it and might not work in complex cases.
So I really want to know and to learn if there are clear methods to do this? I mean, like above simple example, write a conditional function using one condition's output in this function. Any help is highly appreciate.
Your last else is followed by a condition (x > 44 & x < 49), which actually is not correct. If you have (x > 44 & x < 49) there, that means you will execute that statement, and ti = (x-44)*(i_ti_12(49))/(49-44) + (49-x)*(i_ti_12(44))/(49-44) is something independent with your if-else structure.
In that case, when you call i_ti_12(49), your function does not know when the recursion should be terminated since you did not define that case.
You can try the code below:
i_ti_12 <- function(x){
if (x <= 44)
{ti = exp(-13.2238 + 0.152568*x)}
else if (x >= 49)
{ti = -0.01245109 + 0.000315605*x}
else
{ti = (x-44)*(i_ti_12(49))/(49-44) + (49-x)*(i_ti_12(44))/(49-44)}
return(ti)
}
such that
> i_ti_12(49)
[1] 0.003013555

Why does "Sum()" succeed where "+" fails in recursive R function?

I am experimenting with the functional programming paradigm in R. I have defined a function that sums a sequence of integers from n to m. When I use sum() the function returns the expected result:
sumRange <- function(n, m) {
if (n <= m) {
return(sum(n, sumRange((n + 1), m)))
}
}
sumRange(1, 10)
# [1] 55
However, when I use the + operator the function returns numeric(0):
sumRange <- function(n, m) {
if (n <= m) {
return(n + sumRange((n + 1), m))
}
}
sumRange(1, 10)
# numeric(0)
Why does the operator + not work in this recursive function? Is there a way to rewrite the function so that it does?
The issue is that you never specify an else condition, hence at the end of the recursion it appears that R is returning NULL when the if condition fails. Returning 0 as the else condition fixes your problem:
sumRange <- function(n, m) return(ifelse (n <= m, (n + sumRange((n+1), m)), 0))
sumRange(1, 10)
[1] 55
Note that this is essentially defining a base case for your recursion. A base case, when hit, ends the recursion and causes the calls on the stack to be unwound.
To see the issue with the way you phrased your code, try writing out your function explicitly:
sumRange <- function(n, m) {
if (n <= m) {
return(n + sumRange((n+1), m))
}
// but what gets returned if n > m ?
// this is undefined behavior
}
I'm not an R guru, but my understanding is that R was written in C, and C might allow a recursion like this with no else condition. But the behavior is not well defined and you should not be relying on it.
Demo
If there is no return (using a explicit or implicit return statement) is executed, then R functions seems to return a NULL object.
If you add numerical value to a this object, it will simply return numeric(0).
So, what happens in the second case is that when n reaches 11, it returns a NULL object, and goes back adding values to it. But NULL + 10 + 9 .. = numeric(0).
Check this with
no_ret <- function ()
{
# just return nothing
}
obj <- no_ret()
obj
# NULL
class(obj)
# "NULL
new_obj <- obj + 10
new_obj
# numeric(0)
When the first function is executed, the what the sum statement get is
a vector with a NULL in it. For example,
vec <- c(NULL, 10, 9,...) which is actually vec <- c(10, 9, ...), so you get the expected outcome.
> c(NULL, 10:1)
[1] 10 9 8 7 6 5 4 3 2 1
> sum(NULL, 10:1)
[1] 55
> NULL + 10:1
integer(0)

Error message in Bubble sort code in R language

I did some programming work on R language to do the bubble sort. Sometimes it works perfectly without any error message, but sometimes, it shows "Error in if (x[i] > x[i + 1]) { : argument is of length zero". Can any one help me check whats wrong with it? I have attached my code below
example <- function(x) {
n <- length(x)
repeat {
hasChanged <- FALSE
n <- n - 1
for(i in 1:n) {
if ( x[i] > x[i+1] ) {
temp <- x[i]
x[i] <- x[i+1]
x[i+1] <- temp
hasChanged <- TRUE
cat("The current Vector is", x ,"\n")
}
}
if ( !hasChanged ) break;
}
}
x <-sample(1:10,5)
cat("The original Vector is", x ,"\n")
example(x)
The error occurs because you are iteratively decreasing n. Depending on the original vector's order (or lack thereof), n can reach the value of 1 after the last change. In that case, a further reduction of n in the next iteration step addresses the value x[0], which is undefined.
With a minimal correction your code will work properly, without giving error messages. Try to replace the line
if ( !hasChanged ) break;
with
if ( !hasChanged | n==1 ) break
Basically you have two termination criteria: Either nothing has been changed in the previous iteration or n is equal to one. In both cases, a further iteration won't change the vector since it is already ordered.
By the way, in R programming you don't need a semicolon at the end of a command. It is tolerated/ignored by the interpreter, but it clutters the code and is not considered good programming style.
Hope this helps.

Resources