絕對值(abs)、開根號(sqrt)、指數(exp)、對數(log)
abs(-500)
## [1] 500
abs(300)
## [1] 300
sqrt(144)
## [1] 12
exp(2)
## [1] 7.389056
log(6)
## [1] 1.791759
log(exp(10))
## [1] 10
亦可以算出三角函數(sin、cos、tan)
n <- c(sin(1),cos(1),tan(1))
n
## [1] 0.8414710 0.5403023 1.5574077
查詢或定義向量名稱(names)
x <- 1:5
x
## [1] 1 2 3 4 5
names(x) <- c('a','b','c','d','e')
x
## a b c d e
## 1 2 3 4 5
顯示物件的長度(length)
x:物件
value:強制轉換為整數值
x <- 101:2000
length(x)
## [1] 1900
y <- length(diag(5))
y
## [1] 25
數值總和(sum)、累計加總(cumsum)、數值乘積(prod)
x <- 1:10
x1 <- sum(x)
x2 <- cumsum(x)
x3 <- prod(x)
x1
## [1] 55
x2
## [1] 1 3 6 10 15 21 28 36 45 55
x3
## [1] 3628800
最大數值(max)、最小數值(min)
x <- c(1234,5236,5222,5985,1236)
max(x)
## [1] 5985
min(x)
## [1] 1234
產生不同維度的陣列(array)
x:向量
dim:維度
x <- 1:10
array(x,dim = c(2,5)) #產生二維陣列
## [,1] [,2] [,3] [,4] [,5]
## [1,] 1 3 5 7 9
## [2,] 2 4 6 8 10
array(x,dim = c(3,3)) #產生三維陣列
## [,1] [,2] [,3]
## [1,] 1 4 7
## [2,] 2 5 8
## [3,] 3 6 9
產生矩陣(matrix)
nrow:行
ncol:列
byrow:矩陣按照行排列
dimnames:矩陣名稱
matrix(c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16),
nrow = 4,
ncol = 4,
byrow = TRUE,
dimnames = list(c("a1","b2","c3","d4"),c("z1","z2","z3","z4")))
## z1 z2 z3 z4
## a1 1 2 3 4
## b2 5 6 7 8
## c3 9 10 11 12
## d4 13 14 15 16
陣列的合併與轉換
逐列(cbind)
逐行(rbind)
x <- c(1:5)
y <- c(11:15)
cbind(x,y)
## x y
## [1,] 1 11
## [2,] 2 12
## [3,] 3 13
## [4,] 4 14
## [5,] 5 15
rbind(x,y)
## [,1] [,2] [,3] [,4] [,5]
## x 1 2 3 4 5
## y 11 12 13 14 15
改變變數或元素
(as.Date、as.array、as.character、as.numeric…)x:物件 format:格式 origin:起始時間 tz:時區
dates <- c("02/27/94","02/27/98","01/15/98","03/06/95")
as.Date(dates,"%m/%d/%y")
## [1] "1994-02-27" "1998-02-27" "1998-01-15" "1995-03-06"
format(Sys.time(),"%Y-%m-%d %H:%M:%S")
## [1] "2018-05-03 23:47:25"