天天看點

R語言中for、while、if else、switch語句

1、for語句

for (i in 1:5) {
  print("hello world!")
}      
R語言中for、while、if else、switch語句

2、for語句

sum = 0
for (i in 1:100){
  sum = sum + i
}
print(sum)      
R語言中for、while、if else、switch語句

3、for語句

sum = 0
for (i in 1:100) {
  if (i %% 2 == 0)
  {
    sum = sum + i
  }
}
print(sum)      
R語言中for、while、if else、switch語句

4、while語句

i = 5
while (i > 0) {
  print("hello world!")
  i = i - 1
}      
R語言中for、while、if else、switch語句

5、while語句

i = 1
j = 5
while (i <= j) {
  print("hello world!")
  i = i + 1
}      
R語言中for、while、if else、switch語句

 6、while語句

sum = 0
i = 100
while (i > 0) {
  sum = sum + i
  i = i - 1
}
sum      
R語言中for、while、if else、switch語句

 7、while語句

sum = 0
i = 100
while (i > 0) {
  if (i %% 2 != 0){
    sum = sum + i
  }
  i = i - 1
}
print(sum)      
R語言中for、while、if else、switch語句

8、if語句

i  = 1
if (i > 0) {
  print("positive")
}
i = -1
if (i > 0) {
  print("positive")
}      
R語言中for、while、if else、switch語句

9、if語句

i = 1
if (i > 0) {
  print("positive")
} else
  print("<= 0")
i = -7
if (i > 0) {
  print("positive")
} else
  print("<= 0")      
R語言中for、while、if else、switch語句

10、if語句

i = 1
if (i > 0) {
  print("positive")
} else if (i == 0) {
  print("zero")
} else
{
  print("negative")
}
i = 0
if (i > 0) {
  print("positive")
} else if (i == 0) {
  print("zero")
} else
{
  print("negative")
}
i = -1
if (i > 0) {
  print("positive")
} else if (i == 0) {
  print("zero")
} else
{
  print("negative")
}      
R語言中for、while、if else、switch語句

11、if語句

i = 1
ifelse(i > 0, print("positive"), print("<= 0"))
i = 0
ifelse(i > 0, print("positive"), print("<= 0"))      
R語言中for、while、if else、switch語句

12、switch語句

switch (1,"aa","bb","cc","dd")
switch (2,"aa","bb","cc","dd")
switch (3,"aa","bb","cc","dd")      
R語言中for、while、if else、switch語句

繼續閱讀