1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rの便利なライブラリ(dplyr)

Posted at

dplyr

データの抽出・変数の追加・ソートなどの操作を行うライブラリ。

ライブラリ読み込み

library(dplyr)

サンプルデータを作成

> sample1 <- data.frame(x=1:10, y=6:15, z=21:30)
> sample1
    x  y  z
1   1  6 21
2   2  7 22
3   3  8 23
4   4  9 24
5   5 10 25
6   6 11 26
7   7 12 27
8   8 13 28
9   9 14 29
10 10 15 30

<-は代入演算子です。変数sample1data.frameで作成したデータを代入しています。

A %>% B()とすると、Bの第1引数にAが渡されます。

  • filter

データ抽出

sample1のデータから、x > 5の条件を満たす行を抽出します。

> sample2 <- sample1 %>%
  dplyr::filter(x > 5)
> sample2
   x  y  z
1  6 11 26
2  7 12 27
3  8 13 28
4  9 14 29
5 10 15 30

# AND条件は,区切り、OR条件は|区切りで入れます
> sample3 <- sample1 %>%
  dplyr::filter(z < 22 | x > 5, y < 14)
> sample3
  x  y  z
1 1  6 21
2 6 11 26
3 7 12 27
4 8 13 28
  • select

列の抽出

> sample4 <- sample1 %>%
  dplyr::select(x,y)
> sample4
    x  y
1   1  6
2   2  7
3   3  8
4   4  9
5   5 10
6   6 11
7   7 12
8   8 13
9   9 14
10 10 15
  • mutate

変数の追加

> sample5 <- sample1 %>%
  dplyr::mutate(sum = x + y + z)
> sample5
    x  y  z sum
1   1  6 21  28
2   2  7 22  31
3   3  8 23  34
4   4  9 24  37
5   5 10 25  40
6   6 11 26  43
7   7 12 27  46
8   8 13 28  49
9   9 14 29  52
10 10 15 30  55

※適宜追記していきます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?