r - Arguments not being passed to a function within a function -
i having trouble passing arguments function within function. values of arguments not being passed instead "n" , "x[i]" are.
a <- function(n){ x=rep(0:n) for(i in x){ x[i]=cgcd(n,x[i]) } return (sum(x)/(n+1)) } cgcd <- function(n,m){ if((m==n) || (m==0)){ return (1) }else{ r = n %% m return (1 + cgcd(m,r)) } }
my error:
a(10) error in if ((m == n) || (m == 0)) { : missing value true/false needed
your problem not values not being passed properly. can check adding print
statements:
a <- function(n){ x=rep(0:n) for(i in x){ x[i]=cgcd(n,x[i]) } return (sum(x)/(n+1)) } cgcd <- function(n,m){ print(n) # added debugging print(m) # added debugging if((m==n) || (m==0)){ return (1) }else{ r = n %% m return (1 + cgcd(m,r)) } }
this gives following output:
a(10) [1] 10 integer(0) error in if ((m == n) || (m == 0)) { : missing value true/false needed
no, there 2 problems @ work here:
- the
for (... in ...)
construct gives value of entry in list, not index. - array indices in r begin @ 1 rather 0.
fixing these:
a <- function(n){ x=rep(0:n) (i in 1:length(x)) { # index 1 10, rather values of x, zeros. x[i]=cgcd(n,x[i]) } return (sum(x)/(n+1)) } cgcd <- function(n,m){ if((m==n) || (m==0)){ return (1) }else{ r = n %% m return (1 + cgcd(m,r)) } }
and output might expect:
a(10) [1] 2.545455
Comments
Post a Comment