运算符
加减乘除 和py一样
- %% 两个向量求余
v <- c( 2,5.5,6)
t <- c(8, 3, 4)
print(v%%t)
它产生以下结果 -
[1] 2.0 2.5 2.0
- v%/% 两个向量相除求商
v <- c( 2,5.5,6)
t <- c(8, 3, 4)
print(v%/%t)
它产生以下结果 -
[1] 0 1 1
- ^ 将第二向量作为第一向量的指数
v <- c( 2,5.5,6)
t <- c(8, 3, 4)
print(v^t)
它产生以下结果 -
[1] 256.000 166.375 1296.000
- || 称为逻辑OR运算符。 取两个向量的第一个元素,如果其中一个为TRUE,则给出TRUE
v <- c(0,0,TRUE,2+2i)
t <- c(0,3,TRUE,2+3i)
print(v||t)
它产生以下结果 -
FALSE
-
<−
-
or
-
=
-
<<−
称为左分配
v1 <- c(3,1,TRUE,2+3i)
v2 <<- c(3,1,TRUE,2+3i)
v3 = c(3,1,TRUE,2+3i)
print(v1)
print(v2)
print(v3)
它产生以下结果 -
3+0i 1+0i 1+0i 2+3i
3+0i 1+0i 1+0i 2+3i
3+0i 1+0i 1+0i 2+3i
-
->
-
bnor
-
->>
称为右分配
c(3,1,TRUE,2+3i) -> v1
c(3,1,TRUE,2+3i) ->> v2
print(v1)
print(v2)
它产生以下结果 -
3+0i 1+0i 1+0i 2+3i
3+0i 1+0i 1+0i 2+3i
- :
冒号运算符。 它为向量按顺序创建一系列数字。
v <- 2:8
print(v)
它产生以下结果 -
2 3 4 5 6 7 8
- %in% 此运算符用于标识元素是否属于向量
v1 <- 8
v2 <- 12
t <- 1:10
print(v1 %in% t)
print(v2 %in% t)
它产生以下结果 -
TRUE
FALSE
- %*% 此运算符用于将矩阵与其转置相乘。
M = matrix( c(2,6,5,1,10,4), nrow = 2,ncol = 3,byrow = TRUE)
t = M %*% t(M)
print(t)
它产生以下结果 -
[,1] [,2]
[1,] 65 82
[2,] 82 117
获取已安装的所有软件包列表
library()
if 语句
x <- c("what","is","truth")
if("Truth" %in% x) {
print("Truth is found")
} else {
print("Truth is not found")
}
[1] "Truth is not found"
for 循环
v <- LETTERS[1:4]
for ( i in v) {
print(i)
}
[1] "A"
[1] "B"
[1] "C"
[1] "D"
while 循环
v <- c("Hello","while loop")
cnt <- 2
while (cnt < 7) {
print(v)
cnt = cnt + 1
}
[1] "Hello" "while loop"
[1] "Hello" "while loop"
[1] "Hello" "while loop"
[1] "Hello" "while loop"
[1] "Hello" "while loop"
repeat 循环
v <- c("Hello","loop")
cnt <- 2
repeat {
print(v)
cnt <- cnt+1
if(cnt > 5) {
break
}
}
[1] "Hello" "loop"
[1] "Hello" "loop"
[1] "Hello" "loop"
[1] "Hello" "loop"
函数
内置函数的简单示例是seq(),mean(),max(),sum(x)和paste(…)等
# Create a sequence of numbers from 32 to 44.
print(seq(32,44))
# Find mean of numbers from 25 to 82.
print(mean(25:82))
# Find sum of numbers frm 41 to 68.
print(sum(41:68))
[1] 32 33 34 35 36 37 38 39 40 41 42 43 44
[1] 53.5
[1] 1526
用户定义的函数
# Create a function to print squares of numbers in sequence.
new.function <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}
# Call the function new.function supplying 6 as an argument.
new.function(6)
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
[1] 36