Skip to content

Instantly share code, notes, and snippets.

@yutannihilation
Last active November 29, 2018 05:14
Show Gist options
  • Save yutannihilation/b0678948d08f8b82824fb9c7cb49c931 to your computer and use it in GitHub Desktop.
Save yutannihilation/b0678948d08f8b82824fb9c7cb49c931 to your computer and use it in GitHub Desktop.

tibble 2.0.0のas_tibble()の変更点

参考

このgistは、以下のブログ記事からas_tibble()の気になる部分だけを抜き出したものです。 他の変更点について詳しくは元記事を読んでください。

https://www.tidyverse.org/articles/2018/11/tibble-2.0.0-pre-announce/

tibbleとは?

data.frameの改良版。printした結果が見やすい、行を取り出した時に勝手にベクトルに変換したりしない、などの特徴がある。 tidyverseのパッケージ群でよく使われており、知らない間に使われていたりする。

https://tibble.tidyverse.org/articles/tibble.html#tibbles-vs-data-frames

知らない間に使われていたりするが、今回はas_tibble()で明示的にtibbleにするときの話なので、 そういうことをしていなければ気にする必要はない(たぶん。。パッケージ中でas_tibble()してたりすると話は別)

列名がついていないとエラー

元記事からそのまま抜き出して来た例。 行列をtibbleに変換 → 列名を設定、という順序だとエラーになる。tibbleに変換する前に列名を設定しないといけない。

library(tibble)

(m <- cov(unname(iris[-5])))
##            [,1]       [,2]       [,3]       [,4]
## [1,]  0.6856935 -0.0424340  1.2743154  0.5162707
## [2,] -0.0424340  0.1899794 -0.3296564 -0.1216394
## [3,]  1.2743154 -0.3296564  3.1162779  1.2956094
## [4,]  0.5162707 -0.1216394  1.2956094  0.5810063

x <- as_tibble(m)
## Error: Columns 1, 2, 3, 4 must be named.
## Use .name_repair to specify repair.

colnames(x) <- letters[1:4]
## Error in colnames(x) <- letters[1:4]: object 'x' not found

列名がユニークでないとエラー

これも同様。

列名に重複があるdata.frameをtibbleに変換 → 列名を設定、という順序だとエラーになる。tibbleに変換する前に列名の重複を解消しないといけない。

(d <- data.frame(a = 1, a = 2, b = 3, check.names = FALSE))
##   a a b
## 1 1 2 3

x <- as_tibble(d)
## Error: Column name `a` must not be duplicated.
## Use .name_repair to specify repair.

colnames(x) <- c("a_1", "a_2", "b")
## Error in colnames(x) <- c("a_1", "a_2", "b"): object 'x' not found
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment