LoginSignup
2
1

More than 3 years have passed since last update.

データに列を加える・列のデータを書き換える関数(mutate)

Posted at
tags: rBasicLearning

mutate関数

1. mutate関数でできること

mutate関数は, 列にデータを加えることや, 列のデータを書き換えることができます. mutate関数は, dplyrパッケージにあります.

2. 今回使用するデータ

今回は, irisのデータを使用します.

library(datasets)
head(iris)
> head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

3. データに列を加える

対象とするデータセットを第一引数とし, 第二引数以降に加えたいデータを指定します.
今回は具体例として, irisデータに 1~150のデータを加えます.

library(dplyr)
numbers <- 1:150
iris <- mutate(iris, numbers)
head(iris)
> numbers <- 1:150
> iris <- mutate(iris, numbers)
> head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species numbers
1          5.1         3.5          1.4         0.2  setosa       1
2          4.9         3.0          1.4         0.2  setosa       2
3          4.7         3.2          1.3         0.2  setosa       3
4          4.6         3.1          1.5         0.2  setosa       4
5          5.0         3.6          1.4         0.2  setosa       5
6          5.4         3.9          1.7         0.4  setosa       6

4. データを書き換える

対象とするデータセットを第一引数とし, 書き換えたい既存のデータ名を書き, それにデータを与えるとデータが書き換えられる.
今回は具体例として, Sepal.Lengthを2倍にしたものに書き換えます.

library(dplyr)
iris <- mutate(iris, Sepal.Length = Sepal.Length * 2)
head(iris)
> head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1         10.2         3.5          1.4         0.2  setosa
2          9.8         3.0          1.4         0.2  setosa
3          9.4         3.2          1.3         0.2  setosa
4          9.2         3.1          1.5         0.2  setosa
5         10.0         3.6          1.4         0.2  setosa
6         10.8         3.9          1.7         0.4  setosa
2
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
2
1