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 3 years have passed since last update.

【R】 tibbleには何でも入れられる?

Posted at

目次

【R】 dplyr::group_nestを使って集計する
【R】 tibbleには何でも入れられる? <- ここ

はじめに

dplyrパッケージを使っているとよくtibbleに変換されてしまいます。このtibbleにはいろいろなデータを入れることができるようで、tibbleやggplot2で作ったグラフを入れてみます。RStudioを使うとデータを階層的に見ることができるのでお薦めします。

データを作ってみる

サインカーブのデータを作ってみます。

library(tidyverse)
library(magrittr)

sine.data <- tibble(cycle=1:4)
sine.data %<>% mutate(sine=map(cycle, ~(tibble(x=0:99/50) %>% mutate(y=sinpi(x*.x)))))

sine列には、tibbleの中にcycle周期分のsineデータが入っています。
次にそれをグラフにしてみます。

sine.data %<>% mutate(graph=map(sine, ~(ggplot(.x, aes(x,y))+geom_point())))

mapの使い方が分からない時には、目次の一番上のリンクを辿ってみてください。
RStudioでsine.dataの中を見ると
image.png
このようになっています。

4つのグラフを1つにまとめて表示してみます。
リストとして取り出して、arrangeGrobで1つにまとめています。

library(gridExtra)
plot(arrangeGrob(grobs=sine.data$graph), ncol=2)

image.png

データを保存

次にそれぞれのデータをファイルに保存してみます。
一旦リストにしてからwalkを使って保存しています。泥臭くなってしまいましたが、良い方法があれば教えてください。

y <- sine.data %>% select(cycle, sine) %>% as.list %>% transpose
y %>% walk(~(write_csv(.x$sine, paste0("sine", .x$cycle, ".csv"))))

sine1.csv,sine2.csv,sine3.csv,sine4.csvの4つのファイルができているはずです。

データファイルを読み込む

ファイルを作りましたので、それを全部読み込んでみます。

sine.data2 <- tibble(file.name=list.files(pattern=".csv", full.names=T))
sine.data2 %<>% mutate(sine=map(file.name, ~read_csv(.x)))

1行目で拡張子がcsvのファイル名のリストを作って、2行目で読み込んでいます。これらデータを使って上に書いたようにグラフを作ることもできます。
 
また、sine.data2 %>% unnest(sine) で読み込んだデータ全部つなぎ合わせることもできます。

tibbleには列単位で、同じデータタイプである制約がありますが、リストにできるものであれば、tibbleやグラフデータなどいろいろなタイプのでデータが入れられます。

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?