R主要语句

for 语句

#基本语法
for (value in vector) {
  statements
}

LETTERS[]
letters[]

for (i in LETTERS[]){
  print(i)
}

if 语句:由一个布尔表达式,后跟一个或多个语句组成。

#基本语法
if(boolean_expression) {
  // statement(s) will execute if the boolean expression is true.
}


x<- 30L
if(is.integer(x)){
  print("x is an integer")
} 

if..else语句

if(boolean_expression) {
  // statement(s) will execute if the boolean expression is true.
} else {
  // statement(s) will execute if the boolean expression is false.
}


x<- 30.2
if(is.integer(x)){
  print("x is an integer")
} else {
  print("x isnot an integer")
}

if...else if...else语句

if(boolean_expression 1) {
  // Executes when the boolean expression 1 is true.
} else if( boolean_expression 2) {
  // Executes when the boolean expression 2 is true.
} else if( boolean_expression 3) {
  // Executes when the boolean expression 3 is true.
} else {
  // executes when none of the above condition is true.
}

x<- c('what', 'is', 'truth')
if('Truth' %in% x){
  print("Truth is found the first time")
} else if ("truth" %in% x) {
  print("truth is found the second time")
} else{
  print("No truth found")
}
a %in% table
a值是否包含于table中,为真输出TURE,否者输出FALSE

switch语句

#基本语法是 
  switch(expression, case1, case2, case3....)

#若expression的计算结果为整数,且值在1~length(list)之间时,则switch()函数返回列表相应位置的值。若expr的值超出范围,则没有返回值
x <- switch(
  3,
  "first",
  "second",
  "third",
  "fourth"
)
print(x)

switch(3, 3+5, 3*5, 3-5, 3**5)

switch(2*2, mean(1:10), sum(1:10), max(1:10), min(1:10), sqrt(1:10))


#若switch()中的参数list是有名定义时,则当expr等于元素名时,返回变量名对应的值,否则没有返回值。
you.like <- "fruit"
switch(you.like, drink="water", meat = "beef", fruit = "apple", vegetable = "cabbage")

while 循环是首先测试条件满足了才执行循环体中的语句

循环的基本语法是 
  while (test_expression) {
    statement
  }

#举例
v <- c("Hello","while loop")
cnt <- 2
while (cnt < 5) {
  print(v)
  cnt = cnt + 1
}

next

当我们想要跳过循环的当前迭代而不终止它时可以使用next控制语句

v= LETTERS[1:6]
for (i in v) {
  if (i =='D'){
    next
  }
  print(i)
}

repeat 循环一次又一次执行相同的代码,直到满足停止条件

#基本语法是
repeat { 
  commands 
  if(condition) {
    break
  }
}

#举例
v <- c("Hello","loop")
cnt =2
repeat {
  print(v)
  cnt <-cnt+1
  if (cnt>5) {
    break
  }
}

参考

https://www.yiibai.com/r

你可能感兴趣的:(R主要语句)