I am working on a loop coding on R language, and this code involves two functions. If value is radius, period function should be run instead of radius function, and so on.
I coded using my notes from class, but I think it is wrong. I do not get any warnings, but if I do on 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 don’t think I fully understand if and else statement. Does anyone explain it for me? Also what is difference between for statement and if statement?
Thank you for all help.
The problem in this line
where you missing
*operationif/else statementallows your program to decide which code to execute based on some condition. Like in your code, you have two blocks of code the first one is:which you want to execute only if some condition is true i.e.
R == 98, otherwise you execute the other block of code.for statementis used when you want to repeatedly execute a block of code many times. Let’s say you want to print the numbers from1-100, it is not feasible to writeprint(1)print(2)… 100 times!You do this with a simple
forloop, e.g.