LoginSignup
8
6

More than 3 years have passed since last update.

Rの基本(:, seq(), c(), rep() )--- 初心者向け---

Posted at
tags: rBasicLearning

Rの基本

Rでよく使われるものについてまとめましたので, 宜しければ, ご覧ください!

データの代入(<-)

ほとんどの言語では, データの代入は "=" で表されるが,
R言語の場合は "<-" で表される.
ショートカットとしては, "option" + "-"

:(COLON OPERATOR)

左の番号を最小値として取り, 右の番号を最大値として取る.
そして, 左の番号以上・右の番号以下で数字を連続的に取る.

# COLON OPERATOR ###########################################
# Assigns number 0 through 10 to x1
x1 <- 0:10
x1

# Descending order
x2 <- 10:0
x2
> # Assigns number 0 through 10 to x1
> x1 <- 0:10
> x1
 [1]  0  1  2  3  4  5  6  7  8  9 10
> # Descending order
> x2 <- 10:0
> x2
 [1] 10  9  8  7  6  5  4  3  2  1  0

seq()

seq(x)に入力された値を最大値とし, 1からその値まで, 連続した値を取る.
seq(x, y, by = z)で, x から y までを z の値ごとに取っていくというようにする.

# SEQ ######################################################
# Ascending values (duplicates 1:10)
(x3 <- seq(10))

# Specify change in values
(x4 <- seq(30, 0, by = -3))
> # SEQ ######################################################
> # Ascending values (duplicates 1:10)
> (x3 <- seq(10))
 [1]  1  2  3  4  5  6  7  8  9 10
> 
> # Specify change in values
> (x4 <- seq(30, 0, by = -3))
 [1] 30 27 24 21 18 15 12  9  6  3  0

c()

数字の行を鎖状に繋げ, 行ベクトルにする.
"Concatenate" は, 鎖状に繋げるという意味.
c(a, b, …)

# ENTER MULTIPLE VALUES WITH C #############################

# c = concatenate (or combine or collect)

x5 <- c(5, 4, 1, 6, 7, 2, 2, 3, 2, 8)
x5
> x5 <- c(5, 4, 1, 6, 7, 2, 2, 3, 2, 8)
> x5
 [1] 5 4 1 6 7 2 2 3 2 8

rep()

繰り返し, その値を出すことができる.
rep(繰り返したいデータ, 繰り返す回数)
行ベクトルの時は, 一セットごと繰り返す.
各要素ごとに繰り返したいときは, eachで指定する.
rep(繰り返したいデータ, each = x)

# REP ######################################################

x7 <- rep(TRUE, 5)
x7

# Repeats set
x8 <- rep(c(TRUE, FALSE), 5)
x8

# Repeats items in set
x9 <- rep(c(TRUE, FALSE), each = 5)
x9
> # REP ######################################################
> 
> x7 <- rep(TRUE, 5)
> x7
[1] TRUE TRUE TRUE TRUE TRUE
> 
> # Repeats set
> x8 <- rep(c(TRUE, FALSE), 5)
> x8
 [1]  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE
> 
> # Repeats items in set
> x9 <- rep(c(TRUE, FALSE), each = 5)
> x9
 [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE

8
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6