R言語 ベクトル - R Vectors

 

参考:

  • ベクトルに関する Tips 大全 1

ベクトルの作成

a <- c(1, 2, 3, 4, 5)
a
## [1] 1 2 3 4 5
b <- c("dog", "cat", "bee")
b
## [1] "dog" "cat" "bee"
c <- c(TRUE, FALSE, TRUE)
c
## [1]  TRUE FALSE  TRUE
x <- 1:5
x
## [1] 1 2 3 4 5
y <- 5:1
y
## [1] 5 4 3 2 1
z <- -5:5
z
##  [1] -5 -4 -3 -2 -1  0  1  2  3  4  5

seq() - sequence: 数列

seq(from = 1, to = 5, by = 1)
## [1] 1 2 3 4 5
seq(from = 1, to = 5, by = 0.5)
## [1] 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0
seq(from = 1, to = 5, by = 1/2)
## [1] 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0

rep() - replicate: 複製する

rep(1, times = 5)
## [1] 1 1 1 1 1
rep(c(1, 3, 5), times = 5)
##  [1] 1 3 5 1 3 5 1 3 5 1 3 5 1 3 5
rep("dog", times = 5)
## [1] "dog" "dog" "dog" "dog" "dog"
rep(c("dog", "cat"), times = 5)
##  [1] "dog" "cat" "dog" "cat" "dog" "cat" "dog" "cat" "dog" "cat"
rep(TRUE, times = 5)
## [1] TRUE TRUE TRUE TRUE TRUE
rep(c(FALSE, TRUE), times = 5)
##  [1] FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE

ベクトルの要素の数を調べる

length(x)
## [1] 5
length(rep(1, times = 3))
## [1] 3

ベクトルの要素にアクセスする

y[2]
## [1] 4
y[c(1, 3)]  #c()で複数の要素にアクセス
## [1] 5 3
y[-c(1, 3)]  #-c()で複数の要素を取り除く
## [1] 4 2 1
y[y < 4]
## [1] 3 2 1

演算 pt1

z + 2
##  [1] -3 -2 -1  0  1  2  3  4  5  6  7
z - 2
##  [1] -7 -6 -5 -4 -3 -2 -1  0  1  2  3
z * 2
##  [1] -10  -8  -6  -4  -2   0   2   4   6   8  10
z/2
##  [1] -2.5 -2.0 -1.5 -1.0 -0.5  0.0  0.5  1.0  1.5  2.0  2.5
z^2
##  [1] 25 16  9  4  1  0  1  4  9 16 25
sqrt(z)  #平方根
## Warning in sqrt(z): NaNs produced
##  [1]      NaN      NaN      NaN      NaN      NaN 0.000000 1.000000
##  [8] 1.414214 1.732051 2.000000 2.236068
x1 <- c(1, 3, 5)
y1 <- c(2, 4, 6)
x1 + y1
## [1]  3  7 11
x1 - y1
## [1] -1 -1 -1
x1 * y1
## [1]  2 12 30
x1/y1
## [1] 0.5000000 0.7500000 0.8333333

演算 pt2

# 要素の数(長さ)の違うベクトルでは、
# 長いベクトルに合わせて短いベクトルが再利用される
x2 <- c(1, 3, 5)
z2 <- c(1, 2, 3, 4, 5, 6)
z2 + x2
## [1]  2  5  8  5  8 11
z2 - x2
## [1]  0 -1 -2  3  2  1