<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>【gather】タグの記事一覧｜ドクターフント(Dr. Hund)</title>
	<atom:link href="https://brain-storm.space/tag/gather/feed/" rel="self" type="application/rss+xml" />
	<link>https://brain-storm.space</link>
	<description>脳や研究について発信するブログです。This site is for research and statistics.</description>
	<lastBuildDate>Fri, 24 Mar 2023 16:11:21 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.2</generator>

<image>
	<url>https://brain-storm.space/wp-content/uploads/2021/04/cropped-3d0209af428738b78799159b4ce75ad9-32x32.png</url>
	<title>【gather】タグの記事一覧｜ドクターフント(Dr. Hund)</title>
	<link>https://brain-storm.space</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>【R初心者向け】慣れると便利なtidyrのpivot_longerとgatherをやさしく解説！</title>
		<link>https://brain-storm.space/tidyr_gather_pivot_longer/784/</link>
					<comments>https://brain-storm.space/tidyr_gather_pivot_longer/784/#respond</comments>
		
		<dc:creator><![CDATA[brainblog]]></dc:creator>
		<pubDate>Sun, 23 May 2021 03:41:55 +0000</pubDate>
				<category><![CDATA[論文作成・統計]]></category>
		<category><![CDATA[gather]]></category>
		<category><![CDATA[pivot_longer]]></category>
		<category><![CDATA[tidyr]]></category>
		<guid isPermaLink="false">https://brain-storm.space/?p=784</guid>

					<description><![CDATA[データの構造を変える時に有用なのがtidyrというパッケージです。横に広いデータを縦長のデータに変更するpivot_longerまたはgatherを使います。 便利なtidyverseに入っていますので、これを利用してい]]></description>
										<content:encoded><![CDATA[
<p>データの構造を変える時に有用なのがtidyrというパッケージです。横に広いデータを縦長のデータに変更するpivot_longerまたはgatherを使います。</p>



<div class="wp-block-jin-gb-block-box concept-box6">
<p>tidyr本家のホームページにはgatherやspreadの関数の代わりに、<br>pivot_longer()をpivot_wider()を使うことが推奨されています。</p>



<blockquote class="wp-block-quote">
<p>Development on&nbsp;<code>gather()</code>&nbsp;is complete, and for new code we recommend switching to&nbsp;<code><a href="https://tidyr.tidyverse.org/reference/pivot_longer.html">pivot_longer()</a></code>, which is easier to use, more featureful, and still under active development.</p>



<p></p>
<cite>https://tidyr.tidyverse.org/reference/gather.html</cite></blockquote>



<p><span class="marker">pivotal_longerだけ覚えたいという方は途中のgatherを読み飛ばしてください</span>。</p>
</div>



<p>便利なtidyverseに入っていますので、これを利用していきましょう。ではRStudioを開いて準備をしていきます。</p>



<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame2 preset1 animation-fade rtoc_open default" data-id="784" data-theme="jin-child">
			<div id="rtoc-mokuji-title" class=" rtoc_left">
			<button class="rtoc_open_close rtoc_open"></button>
			<span>Contents</span>
			</div><ol class="rtoc-mokuji decimal_ol level-1"><li class="rtoc-item"><a href="#rtoc-1">データセットの準備</a></li><li class="rtoc-item"><a href="#rtoc-2">データのはじめにIDを入れる</a></li><li class="rtoc-item"><a href="#rtoc-3">gatherで縦のデータにする</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-4">tidyrパッケージのgatherを使っていきましょう</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-5">Pivotal_longerで縦長のデータに変形をする</a></li></ol></div><h2 id="rtoc-1"  class="wp-block-heading">データセットの準備</h2>



<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/05/pexels-photo-5965839-1024x682.jpeg" alt="crop diverse female students fulfilling homework together in park" class="wp-image-808" width="512" height="341"/></figure>



<p>まずは作業ディレクトリをセットして、tidyverseを起動しています。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
setwd(&quot;~/Rpractice/&quot;)
library(tidyverse)
</pre></div>


<p>次にアヤメのサンプルデータを使っていきましょう。head()でデータのはじめのほうを表示します。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
a &lt;- iris
&gt; head(a)
  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
</pre></div>


<p>summary()も便利です。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
&gt; summary(a)
  Sepal.Length    Sepal.Width     Petal.Length    Petal.Width          Species  
 Min.   :4.300   Min.   :2.000   Min.   :1.000   Min.   :0.100   setosa    :50  
 1st Qu.:5.100   1st Qu.:2.800   1st Qu.:1.600   1st Qu.:0.300   versicolor:50  
 Median :5.800   Median :3.000   Median :4.350   Median :1.300   virginica :50  
 Mean   :5.843   Mean   :3.057   Mean   :3.758   Mean   :1.199                  
 3rd Qu.:6.400   3rd Qu.:3.300   3rd Qu.:5.100   3rd Qu.:1.800                  
 Max.   :7.900   Max.   :4.400   Max.   :6.900   Max.   :2.500                  
&gt; 
</pre></div>


<p>Minは最小値、1st Quは第一四分位数、Medianは中央値、Meanは平均値、3rd Quは第三四分位数、Maxは最大値です。QuはQuartileですね。</p>



<p>Speciesにsetosa、versicolor、virginicaがあり、それぞれ50ずつのデータが入っていることもわかります。データすべてを確認するには、View()を使ってみてください。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
View(a)
</pre></div>


<h2 id="rtoc-2"  class="wp-block-heading">データのはじめにIDを入れる</h2>



<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/05/pexels-photo-2277784-1024x682.jpeg" alt="time for change sign with led light" class="wp-image-810" width="512" height="341"/></figure>



<p>これから並び替えをしますので、IDを入れておくと混乱は避けることができます。またspreadを使うときにもIDとなるものが必要です。</p>



<p>tidyverseの中のdplyrを使ってみます。その中に<span class="marker"><code>mutate</code></span>というファンクションがあります。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
a2 &lt;- a %&gt;%
dplyr::mutate(a, ID=rownames(a)) 
</pre></div>


<p>またはtibbleというパッケージの<span class="marker"><code>rownames_to_column</code></span>でもいけます</p>



<p><code>tibble</code>もtidyverseの中の一つです。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
a2 &lt;- a %&gt;%
tibble::rownames_to_column(var = &quot;ID&quot;)
</pre></div>


<p>初心者の間はこういうものがあるんだ、くらいの感覚でいいと思います。またわからなくなったらここに戻ってきて参照してください。</p>



<div class="wp-block-jin-gb-block-border jin-sen"><div class="jin-sen-dashed" style="border-width:3px;border-color:#f48789"></div></div>



<div class="wp-block-jin-gb-block-box concept-box1">
<p>%>%はパイプまたはパイプ演算子と呼びます。一つ前の出力を次のプログラムに代入します。</p>
</div>



<p>パイプを使うことでデータを指定すべきことを省略できます。一つ前の出力をそのまま代入できる便利モノです。下の2つは同じ意味です。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
a2 &lt;- a %&gt;%
tibble::rownames_to_column(var = &quot;ID&quot;)
</pre></div>

<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
a2 &lt;- tibble::rownames_to_column(a, var = &quot;ID&quot;)
</pre></div>


<p>RStudioでは<span class="marker">Shift + Ctrl + M</span>を押すと%&gt;%が出てきます。出力を縦に流れるようにつないで行くことができます。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
x &lt;- a %&gt;% 
  group_by(Species) %&gt;% 
  dplyr::summarise_each(funs(mean, sd), Sepal.Length, Sepal.Width)

&gt; x
# A tibble: 3 x 5
  Species    Sepal.Length_mean Sepal.Width_mean Sepal.Length_sd Sepal.Width_sd
  &lt;fct&gt;                  &lt;dbl&gt;            &lt;dbl&gt;           &lt;dbl&gt;          &lt;dbl&gt;
1 setosa                  5.01             3.43           0.352          0.379
2 versicolor              5.94             2.77           0.516          0.314
3 virginica               6.59             2.97           0.636          0.322
&gt; 
</pre></div>


<div class="wp-block-jin-gb-block-border jin-sen"><div class="jin-sen-dashed" style="border-width:3px;border-color:#f48789"></div></div>



<h2 id="rtoc-3"  class="wp-block-heading">gatherで縦のデータにする</h2>



<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/05/Charton-Crafts-1-1024x493.jpg" alt="" class="wp-image-812" width="768" height="370"/></figure>



<h3 id="rtoc-4"  class="wp-block-heading">tidyrパッケージのgatherを使っていきましょう</h3>



<p><code>df %>% gather("key", "value", x, y, z)</code>で使います。それではアヤメデータで使っていきましょう。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
b &lt;- a2 %&gt;%
  tidyr::gather(key = FlowerAtt, 
                value = Values, 
                Sepal.Length:Petal.Width)

&gt; head(b)
  ID Species    FlowerAtt Values
1  1  setosa Sepal.Length    5.1
2  2  setosa Sepal.Length    4.9
3  3  setosa Sepal.Length    4.7
4  4  setosa Sepal.Length    4.6
5  5  setosa Sepal.Length    5.0
6  6  setosa Sepal.Length    5.4
&gt; 
</pre></div>


<p>このkey、valueがはじめのうちはよくわからないと思います。</p>



<p>後ろ(下)から説明をします。</p>



<p><span class="marker">3番目の入力Sepal.Length:Petal.Widthは縦に並べたい変数名</span>です。</p>



<p><span class="marker">2番目のvalueは変数名で、数値の入った列に名前をつけます</span>。</p>



<p><span class="marker">最初のkeyは横並びしていた変数名が縦に並んだ、その列について名前をつけます</span>。</p>



<p>FlowerAttのAttはAttributeですが、keyは自分の付けたい名前をつけることができます。</p>



<div class="wp-block-jin-gb-block-box concept-box5">
<p>コロンの使い方は、例えばABCDEと並んでいたときに、A:Eと書くというもので、下の書き方と同じです。</p>



<p>Sepal.Length:Petal.WidthはSepal.Length、Sepal.Width、Petal.Length、Petal.Widthになります。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
b &lt;- a2 %&gt;%
  tidyr::gather(key = FlowerAtt, 
                Value = Values, 
                Sepal.Length, Sepal.Width, Petal.Length, Petal.Width)
</pre></div></div>



<p>次になにかを残したいときは、項目名の前に-をつけます。例えばSepal.WidthとPetal.Lengthを残したいときには次のようにかきます。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
c &lt;- a2 %&gt;%
  tidyr::gather(key = FlowerAtt, 
                value = Values, 
                Sepal.Length:Petal.Width, 
                -Sepal.Width, -Petal.Length)

&gt; head(c)
  ID Sepal.Width Petal.Length Species  FlowerAtt Values
1  1         3.5          1.4  setosa Sepal.Length    5.1
2  2         3.0          1.4  setosa Sepal.Length    4.9
3  3         3.2          1.3  setosa Sepal.Length    4.7
4  4         3.1          1.5  setosa Sepal.Length    4.6
5  5         3.6          1.4  setosa Sepal.Length    5.0
6  6         3.9          1.7  setosa Sepal.Length    5.4
&gt;
</pre></div>


<p>除外したSepal.WidthとPetal.Lengthが残っているのがわかります。</p>



<h2 id="rtoc-5"  class="wp-block-heading">Pivotal_longerで縦長のデータに変形をする</h2>



<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/05/Charton-Crafts-1024x493.jpg" alt="" class="wp-image-811" width="768" height="370"/></figure>



<p>gatherは直感的にわかりにくく、また引数も覚えにくいので、開発者自身も毎回ドキュメンテーションを見ないといけない、という趣旨のことが書いてあります(笑)。</p>



<p>それをより使いやすくしたのが、<code>pivot_longer</code>です。こちらだけ覚えていいと思います。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
pivot_longer(data, cols, names_to = &quot;name&quot;, values_to = &quot;value&quot;)
</pre></div>


<p><span class="marker"><code>cols</code>は縦長に変形をする列を記載します</span>(アヤメのデータではSepal.Length、Sepal.Widthなどです)。</p>



<p><span class="marker"><code>names_to</code>では、縦長にした列名の列に新しい名前をつけます</span>(上の例ではFlowerAttとつけていました)。</p>



<p><span class="marker"><code>values_to</code>は縦長になった変数の列に名前をつけます</span>(Valuesとつけていました)。</p>



<p>ではやってみましょう。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
A &lt;- a2 %&gt;% 
  pivot_longer(cols = Sepal.Length:Petal.Width, 
               names_to = &quot;FlowerAtt&quot;, 
               values_to = &quot;Values&quot;)

&gt; head(A)
# A tibble: 6 x 4
  ID    Species FlowerAtt    Values
  &lt;chr&gt; &lt;fct&gt;   &lt;chr&gt;         &lt;dbl&gt;
1 1     setosa  Sepal.Length    5.1
2 1     setosa  Sepal.Width     3.5
3 1     setosa  Petal.Length    1.4
4 1     setosa  Petal.Width     0.2
5 2     setosa  Sepal.Length    4.9
6 2     setosa  Sepal.Width     3  
&gt; 
</pre></div>


<p><code>cols</code>の複数指定の方法はいくつかあるようですが、 個別に指定する方法を示します。<br><code>cols = c()</code>で項目名を個別に指定をすることができます。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: Code example; notranslate">
A &lt;- a2 %&gt;% 
  pivot_longer(cols = c(Sepal.Length, Sepal.Width, 
                        Petal.Length, Petal.Width),
               names_to = &quot;FlowerAtt&quot;, 
               values_to = &quot;Values&quot;)

</pre></div>


<p>変形する列を<code>cols</code>で指定しましたが、変形しない列を-で指定することもできます。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
B &lt;- a2 %&gt;% 
  pivot_longer(cols = -c(ID, Species), 
               names_to = &quot;Measurement&quot;, 
               values_to = &quot;Values&quot;)

&gt; head(B)
# A tibble: 6 x 4
  ID    Species Measurement  Values
  &lt;chr&gt; &lt;fct&gt;   &lt;chr&gt;         &lt;dbl&gt;
1 1     setosa  Sepal.Length    5.1
2 1     setosa  Sepal.Width     3.5
3 1     setosa  Petal.Length    1.4
4 1     setosa  Petal.Width     0.2
5 2     setosa  Sepal.Length    4.9
6 2     setosa  Sepal.Width     3  
&gt; 
</pre></div>


<p>今回細かいオプションは説明をしていませんが、これらができれば十分に便利だと思います。また別の記事でspreadとpivot_widerを紹介します。</p>



<p>お役に立ちましたら幸いです。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://brain-storm.space/tidyr_gather_pivot_longer/784/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
