LoginSignup
1
2

More than 5 years have passed since last update.

Rの変数操作と型

Last updated at Posted at 2015-06-25

変数への代入

x <- 5 # => 5
x = 5 # => 5

ls() : 変数一覧
rm(x) : 変数の消去

  • 数値
  • 文字列

  • ベクトル
  • 行列
  • リスト
  • データフレーム

  • NULL
  • TRUE/FALSE
  • NA(欠損値)
  • NaN(非数)
  • Inf(無限大)

数値と文字列

数値

10 / 3      # => 3.3333
10 %/% 3    # => 3 (商) 
10 %% 3 # => 1 (余)

2 ^ 4       # => 16
cos(1)  # => 0.5403023
sqrt(2)     # => 1.414214 (平方根)
round(2.55) # => 3

文字列

"abcdefg"
paste("a","b","c")          # => "a b c"
paste("a","b","c",sep="")   # => "abc"

as.charactor(x)             # => "5"
as.numeric(x)                   # => 5

ベクトル

ベクトルの作成

v <- c(1,3,5)                   # => 1 3 5
v[2]                            # => 3
v <- c("abc", "bdef")
v <- c(TRUE, FALSE)
length(v)                   # => 2
v <- 1:10                       # => 1 2 3 4 5 6 7 8 9 10
v <- 1:-10                  # => 1 0 -1 -2 ..       -10
v <- seq(1, 10, by=2)       # => 1 3 5 7 9
v <- seq(1, 10, length=5)   # => 1.00 3.25 5.50 7.75 10.00
v <- rep(1:5, times=3)      # => 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
v <- rep(1:5, length=5)     # => 1 2 3 4 5

ベクトルの演算

x <- c(1, 3, 5)
y <- c(1, 2, 3)

x * 2               # => 2 6 10
x - 1               # => 0 2 4

x + y               # => 2 5 8
x > y               # => FALSE TRUE TRUE
x %in% y            # => TRUE FALSE FALSE

union(x,y)      # => 1 2 3 5
intersect(x,y)  # => 1 3
setdiff(x,y)        # => 2 5
setequal(x,y)   # => FALSE

因子ベクトル

カテゴリー付きのベクトル
あとで因子分析ができる

factor(x) : xベクトルから因子ベクトルを作成
levels(x.fc) : レベルを表示
odered : 大小関係をつける

x <- c("S","M","M","L","S")
x.fc <- factor(x)               # => Levels L M S

levels(x.fc)                        # => L M S

x.fc <- factor(x, levels=c("S","M","L"))

levels(x.fc)                        # => S M L

x.or <- odered(x, levels=c("S","M","L"))

levels(x.or)                        # => S < M < L

参考

1
2
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
1
2