Thursday, 15 January 2015

function - R language: If and else statement (loop) -



function - R language: If and else statement (loop) -

i working on loop coding on r language, , code involves 2 functions. if value radius, period function should run instead of radius function, , on.

i coded using notes class, think wrong. not warnings, if on console:

r<-98 orbit(r)

i message:

error in orbit(r) : effort apply non-function

this function code:

# 2 functions: period , radius # if value input period (in minutes), radius function should used (radius(r)) # if value input radius (in km), period function should used (period(r)) # r radius in km or period in minutes orbit <- function(r){ g <-6.673*10^-11 m <- 5.972*10^24 # in kg if(r == 98){ omega <- 2*pi/r # pr period 1 rotation radi <- (g*m/omega^3)(1/3) print(radi) } else { peri <- 2*pi*sqrt(r^3/g*m) print(peri) } }

i don't think understand if , else statement. explain me? difference between statement , if statement?

thank help.

the problem in line

radi <- (g*m/omega^3)*(1/3)

where missing * operation

if/else statement allows programme decide code execute based on condition. in code, have 2 blocks of code first 1 is:

omega <- 2*pi/r # pr period 1 rotation radi <- (g*m/omega^3)(1/3) print(radi)

which want execute only if status true i.e. r == 98, otherwise execute other block of code.

for statement used when want repeatedly execute block of code many times. let's want print numbers 1-100, not feasible write print(1) print(2) ... 100 times!

you simple for loop, e.g.

for(i in 1:100){ print(i) }

r function loops if-statement

No comments:

Post a Comment