R-language: if and else statement (loop)

I am working on coding in the R language, and this code includes two functions. If the value is equal to the radius, the period function should be run instead of the radius function, etc.

I encoded my notes from the class, but I think this is wrong. I do not get any warnings, but if I do this on the console:

R<-98 orbit(R) 

I will get this message:

 Error in orbit(R) : attempt to apply non-function 

This is my function code:

 # Two functions: period and radius # If a value you input is a period (in minutes), radius function should be used (radius(R)) # If a value you input is a radius (in km), period function should be used (period(R)) # R is 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 is period for one rotation Radi <- (G*M/omega^3)(1/3) print(Radi) } else { Peri <- 2*pi*sqrt(R^3/G*M) print(Peri) } } 

I do not think that I fully understand the if and else statement. Anyone explain this to me? Also what is the difference between a for and if statement?

Thanks for the help.

+4
source share
1 answer

The problem is in this line.

 Radi <- (G*M/omega^3)*(1/3) 

where the operation is missing *

if/else statement allows your program to decide which code to execute based on some condition. As in your code, you have two blocks of code, the first of which:

 omega <- 2*pi/R # pr is period for one rotation Radi <- (G*M/omega^3)(1/3) print(Radi) 

which you want to fulfill only if any condition is true, i.e. R == 98 , otherwise you are executing another block of code.

for statement used if you want to repeatedly execute a block of code many times. Let's say you want to print numbers from 1-100 , it is not possible to write print(1) print(2) ... 100 times!

You do this with a simple for loop, for example.

 for(i in 1:100){ print(i) } 
+5
source

All Articles