random walk function in R [closed] - r

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a random walk function
random.walk = function(n){
return(cunsum(c(0, sample(c(-1, 1), size = n-1, replace =TRUE))))
}
I would like to make recursive random walk function.
what I did was
recursive.rwalk=function(n){
return(random.walk(n-1) + random.walk(n))
}
but then Im getting warning message.
Please help me out!
Thanks

You are trying to add two vectors of different lengths: n-1 and n in this line: random.walk(n-1) + random.walk(n). R is warning you that the first element of the first vector is added to the last element of the second vector (value recycling).

Altough it's obviously not a good idea to calculate a random walk recursively in R, here is how you would do that. First of all you have to recursively call the recursive.rwalk function, not the random.walk function. Next, you still need to sample each step of the way. And finally you need to tell the function when to stop recursively calling itself. Here's one way that will work:
recursive.rwalk=function(n){
if (n==0) return(0)
rw <- recursive.rwalk(n-1)
return(c(rw, rw[n-1]+sample(c(-1,1), 1)))
}
set.seed(123)
recursive.rwalk(5)
## [1] 0 1 0 1 2

Related

How to save a calculation to a variable using variables that have not been defined yet? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
Let's say I have a script, where I have a calculation like this:
calculation = c(
a*b +
c*d +
e*f
)
And then in another script I want to call that calculation using the source command.
I get an error saying "Object 'a' not found". What am I doing wrong?
Edit: I don't want to make a function, because this specific calculation is used as input in a complex program in r (apollo) - the input specifies a utility function in a logit regression.
You can capture your expression using expression(), then when you're ready, evaluate using eval():
calculation <- expression(a*b + d*e + f*g)
a <- 1
b <- 2
d <- 3
e <- 4
f <- 5
g <- 6
eval(calculation)
# 44

how to modify argument in function? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have to solve this:
Modify the cumulative risk calculator of exercise 1 so that the
argument t has the value 5 if user does not give it any other value.
cumulative risk = 1-exp(-1/10000*t).
where the exercise 1 was
We can estimate the cumulative risk of an certain event using the
exponential formula 1-exp(-1/10000*t) where t is the time to the
event. Create a function ans(t), which returns the risk at time t.
To assign a pre-specified value to t you can use
function(t=5){
answer<-1-exp(-1/10000*t)
return(answer)
}
You can define a variable as 5, then call the function using that variable, and save the result somewhere, i.e.
function.exp <- function(t) {
answer <- 1 - exp(-1 / 10000 * t)
return(answer)
}
x = 5
m <- function.exp(x)
m
Result
[1] 0.000499875
Hope that helps :)

Formula to find square root of a natural number using only addition and subtraction [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
How to use only addition and subtraction to find out square root of a natural number?
Thanks.
[I have looked over the internet but i didn't find any content related to this problem.]
Explanation to my problem: I want to create a c function which will receive only a natural number and return square root of it.
You may say to use the "sqrt" function but i just thought of creating one which will utilize addition and subtraction operator to create the square root.
You don't have to write the program, just writing the formula for it will be just fine. Thanks.
Update: This question is not specifically about coding rather about mathematics.(I tagged "c" as it had some link but this question is NOT about coding.)
n2 is the equivalent of the sum of the n first odd numbers.
You can iterate over the n (consequently adding only the next odd number to the previously calculated sum) until the square is equal or exceeds your number.
k = 0
sum = 0
while sum < target:
k += 1
sum += 2k-1
if sum > target:
the target doesn't have integer root
else:
k is the square root
We can use the fact that (n+1)² = n² + 2n + 1.
def sqrt(n):
k = 0
s = 0
while s <= n:
s = s+k+k+1
k = k+1
return k-1
print (sqrt(0)) # 0^2
print (sqrt(1)) # 1^2
print (sqrt(2)) # (1.4142135623730951...)^2
print (sqrt(144)) # 12^2
print (sqrt(169)) # 13^2
print (sqrt(196)) # 14^2
print (sqrt(255)) # 15^2
print (sqrt(1000)) # (31.622776601683793...)^2
print (sqrt(2000)) # (44.721359549995796...)^2
UPD
Sorry, I thought you were asking for code :)

logstar function_the iterate of the natural logarithm_r [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
In R, I would like to create a function that returns the smallest n such that the n-th repetition of the natural logarithm gives a value smaller than one. Ex.: fun(9182) = 3 because ln(ln(ln(9182))) = 0,793 < 1.
Any suggestions will be appreciated!
logstar<-function(x){if (x<1) 0 else 1 + logstar(log(x))}
#mrip's answer works well for single values. If you'd like a function that works for vectors, you'll want to use ifelse() rather than if:
> logstar <- function(x){ifelse(x<1,0,1 + logstar(ifelse(x<1,x,log(x))))}
> x = c(0.5,1,100,10000,1E8)
> logstar(x)
[1] 0 1 3 3 4
The ifelse() in the recursive call to logstar() prevents log() from generating NaN in some cases.

how to do looping in R [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Hey guys i want to do looping in R ; can anybody help me out
For eg i have sum of points and i want no of empid in 0-10 % of sum of points and so on ;how to do in R
For eg I have data as
empid sumofpoints
1 10
2 30
I want data as
percentageofsumpoints countofempid
0-10 4
11-20 5
21-30 6
and so on....
How to do it in R ,do i have to install any package for it
No need to install package.See http://nunn.rc.fas.harvard.edu/groups/pica/wiki/1f131/
Simple for loop
for (i in 1:10){
print(i)
}
In your example, asssuming your data is stored in a dataframe called df
res <- NULL
groups <- c(0,10,20,30,40,...)
for (i in 2:length(groups)){
res <- rbind(res,c(paste(groups[i],groups[i-1],sep="-"),nrow(df[df$sumofpoints <= groups[i] & df$sumofpoints > groups[i-1],])))
}
You can also use apply functions if you want to avoid for statements. This example I have taken directly from the help files
x <- cbind(x1 = 3, x2 = c(4:1, 2:5))
dimnames(x)[[1]] <- letters[1:8]
apply(x, 2, mean, trim = .2)
EDIT further to this how to avoid loops
For large dataset, refer to the package foreach. This allows for a sequential loop set-up using %do% or a parallel set-up (faster for large datasets) using %dopar%.
http://cran.r-project.org/web/packages/foreach/vignettes/foreach.pdf
For parallel computing, be mindful that you will need a backend such as "doParallel" or "DoSNOW". There is also "doMC" which only works with operating systems that support the
fork system call (which means that Windows isn't supported).

Resources