当前位置: 动力学知识库 > 问答 > 编程问答 >

recursion - R - converting recursive code to functional programming

问题描述:

I want to do a conditional cumsum. I originally thought I could use the Reduce function but I wasnt able to. To explain clearly :

a <- rep(1,5)

b <- rnorm(n=5,mean=0.5)

c <- rep(2,5)

d <- rep(0.5,5)

Reduce( '+', a, init=200 , accumulate=TRUE)

Results in

[1] 200 201 202 203 204 205

This is just like a simple cumsum. But what I actually want is a conditional cumsum:

The recursion is defined as :

 x0 = 200

index = 0

function (x) {

index = index + 1

if( x is between 200 and 202 ) return x + a[index]

else if(x is between 202 and 204) return x + b[index]

else if(x is between 204 and 206) return x + c[index]

else return x + d[index]

}

The expected result could be something like this (of course it will never be the same because of the randomness.

 [1] 200 201 202.3 203.8 204.1 205

For those who are interested, the answer can be found here :

Convert simple recursive relation to functional program

I can't seem to find a way to mark this question as closed since the moderators keep on deleting whatever I add without suggesting a proper way to close.

网友答案:

I don't think you need Reduce here. Here an example that explain a use case of Reduce:

 Reduce(paste,list(1:3,letters[1:3],LETTERS[1:3]))
[1] "1 a A" "2 b B" "3 c C"

I think what you try to do xan be done using ifelse, it is vectorized. Here for example a conditional cumultive sum of a and b starting from init value.

a <- rep(1,5)
b <- rep(0.01,5)
init <- 200
x <- seq_along(a)
cumsum(c(init,ifelse( x %% 2 ,a[x],  b[x])))
[1] 200.00 201.00 201.01 202.01 202.02 203.02

Of course if you have multiple condition:

  • Use multiple condition: x %% 2 & x^2 < 5
  • Use nested ifelse : ifelse( x %% 2 ,ifelse(x^2 <2, a[x], b[x]),1)
分享给朋友:
您可能感兴趣的文章:
随机阅读: