6
12

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 unique()で重複のない値を取り出す

Posted at

unique()使い方

unique()にベクトルとかを入れると重複しない値を返してくれる
例: (RStudioで実行)

> unique(iris$Species)
[1] setosa     versicolor virginica 
Levels: setosa versicolor virginica
> unique(iris['Species'])
       Species
1       setosa
51  versicolor
101  virginica

重複のない値の数を数えるときは

> length(unique(iris$Species))
[1] 3

とする

> length(unique(iris['Species']))
[1] 1

としてしまうと間違った値が出てしまうので注意。なぜかというとlength()はベクトルの長さを返す関数で、iris['Species']はlist型のため。

全ての列の重複しない値の個数を表示

> lapply(iris, function(x) length(unique(x)))
$Sepal.Length
[1] 35

$Sepal.Width
[1] 23

$Petal.Length
[1] 43

$Petal.Width
[1] 22

$Species
[1] 3

もしくは

> apply(iris, 2, function(x) length(unique(x)))
Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
          35           23           43           22            3 
6
12
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
6
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?