R语言中级--自定义方程

#求电费,<50,85折,50--120,50元/度,>120,1.15倍
myfunction <- function(deg,price = 50){
  if(deg>120)
    energyprice = deg*price*1.15
  else 
    if(deg<80)
    energyprice = deg*price*0.85
    else 
    energyprice = deg*price
  return(round(energyprice))}
myfunction(100)


myfunction2 <- function(deg,price = 50, poor = FALSE) 
{energyprice = deg*price
if (deg > 100)
  energyprice = deg*price*1.15
else
  if (poor == TRUE)
    energyprice = energyprice*0.85*0.7
  else
    energyprice = energyprice*0.85
  return(round(energyprice))}
myfunction2(80,poor = TRUE)

#给定一个数x,求x*(x-1)*...*2*1
myfunction3 <- function(x)
{ if (x == 0)
  x_sum = 1
else 
  x_sum = x*myfunction3(x-1)
return(x_sum)}
myfunction3(4)

ifelse(condition,statement1,statement2)

#求1到n 之和
myfunction4 <- function(n)
{sum = 0
for (i in 1:n)
  sum = sum + i
return(sum)}
myfunction4(100)
sum(1:100)

#同fun4
myfunction5 <- function(n)
{sum = 0
while (n >= 0) {      
  sum = sum + n
  n = n - 1}  
return(sum)
}
myfunction5(100)

#同fun4
myfunction6 <- function(n)
{sum = 0
repeat{ 
  sum = sum + n
  n = n - 1
  if(n == 0) break   
}                    
return(sum)}
myfunction6(100)

#奇数之和
myfunction7<- function(n)
{sum=0
for(i in 1:n)
{
  if(i %%2 !=0) next   
  sum=sum+i
}
return(sum)
}
myfunction7(100)
x<- c(1:100)
x %% 2 

  

Valar morghulis
原文地址:https://www.cnblogs.com/super-yb/p/11047938.html