Rベクトル


ベクトル

ベクトルは、単に同じタイプのアイテムのリストです。

アイテムのリストをベクトルに結合するには、c()関数を使用してアイテムをコンマで区切ります。

以下の例では、文字列を組み合わせたfruitsというベクトル変数を作成します。

# Vector of strings
fruits <- c("banana", "apple", "orange")

# Print fruits
fruits

この例では、数値を組み合わせたベクトルを作成します。

# Vector of numerical values
numbers <- c(1, 2, 3)

# Print numbers
numbers

シーケンス内の数値を含むベクトルを作成するには、次の:演算子を使用します。

# Vector with numerical values in a sequence
numbers <- 1:10

numbers

シーケンス内の小数を使用して数値を作成することもできますが、最後の要素がシーケンスに属していない場合は使用されないことに注意してください。

# Vector with numerical decimals in a sequence
numbers1 <- 1.5:6.5
numbers1

# Vector with numerical decimals in a sequence where the last element is not used
numbers2 <- 1.5:6.3
numbers2

結果:

[1] 1.5 2.5 3.5 4.5 5.5 6.5
[1] 1.5 2.5 3.5 4.5 5.5

以下の例では、論理値のベクトルを作成します。

# Vector of logical values
log_values <- c(TRUE, FALSE, TRUE, FALSE)

log_values

ベクトルの長さ

ベクトルに含まれるアイテムの数を確認するには、次のlength()関数を使用します。

fruits <- c("banana", "apple", "orange")

length(fruits)

ベクトルを並べ替える

ベクトル内のアイテムをアルファベット順または数値順に並べ替えるには、次のsort()関数を使用します。

fruits <- c("banana", "apple", "orange", "mango", "lemon")
numbers <- c(13, 3, 5, 7, 20, 2)

sort(fruits)  # Sort a string
sort(numbers) # Sort numbers

アクセスベクトル

括弧内のインデックス番号を参照することで、ベクターアイテムにアクセスできます[]最初のアイテムにはインデックス1があり、2番目のアイテムにはインデックス2があります。

fruits <- c("banana", "apple", "orange")

# Access the first item (banana)
fruits[1]

c()次の関数を使用してさまざまなインデックス位置を参照することにより、複数の要素にアクセスすることもできます。

fruits <- c("banana", "apple", "orange", "mango", "lemon")

# Access the first and third item (banana and orange)
fruits[c(1, 3)]

負のインデックス番号を使用して、指定されたものを除くすべてのアイテムにアクセスすることもできます。

fruits <- c("banana", "apple", "orange", "mango", "lemon")

# Access all items except for the first item
fruits[c(-1)]

アイテムを変更する

特定のアイテムの値を変更するには、インデックス番号を参照してください。

fruits <- c("banana", "apple", "orange", "mango", "lemon")

# Change "banana" to "pear"
fruits[1] <- "pear"

# Print fruits
fruits

ベクトルを繰り返す

ベクトルを繰り返すには、次のrep()関数を使用します。

各値を繰り返します。

repeat_each <- rep(c(1,2,3), each = 3)

repeat_each

ベクトルのシーケンスを繰り返します。

repeat_times <- rep(c(1,2,3), times = 3)

repeat_times

各値を個別に繰り返します。

repeat_indepent <- rep(c(1,2,3), times = c(5,2,1))

repeat_indepent

シーケンスされたベクトルの生成

:上の例の1つは、演算子を使用してシーケンス内の数値を使用してベクトルを作成する方法を示しています。

numbers <- 1:10

numbers

シーケンスでより大きなまたはより小さなステップを作成するには、次のseq()関数を使用します。

numbers <- seq(from = 0, to = 100, by = 20)

numbers

注:このseq()関数には3つのパラメーターがあります。fromはシーケンスの開始to場所、はシーケンスの停止場所、はシーケンスbyの間隔です。