LoginSignup
5
5

More than 5 years have passed since last update.

R でピボットテーブルを作成

Last updated at Posted at 2016-04-18

表からピボットテーブルを作る方法

なお、Fink からインストールした r-base32 を使用しています。

データを CSV 形式で保存。

bloodpressure.csv
name,sbp,dbp,hr,temp,date,year,month
yamada,158,96,81,62,31,2016,3
yamada,135,72,81,61,30,2016,3
yamada,147,89,72,63,31,2015,3
yamada,157,98,79,62,30,2015,3
yamada,121,81,76,61,29,2015,3
sato,89,48,57,66,30,2016,3
sato,144,84,81,64,29,2016,3
sato,139,103,110,65,30,2015,3
sato,147,87,74,66,30,2015,3
sato,134,82,70,59,29,2015,3
sato,140,83,65,49,28,2015,3

ターミナルを開き、

$ cd Desktop

$ R-3.2

R 内では、以下のコマンドを入力します。

bloodpressure.r
library("reshape2")

bloodpressure <- read.csv("bloodpressure.csv", header=TRUE, sep=",", na.strings="", dec=".", strip.white=TRUE)

sbp_table<-dcast(bloodpressure,name~year,value.var="sbp",mean)

sbp_table

と入力して確認すると、

    name     2015  2016
1   sato 140.0000 116.5
2 yamada 141.6667 146.5

と表示されます。

name~year

のところを、

name~year+month+date

とすると、2015_3, 2016_3 のように表示されます (サンプルのデータでは3月しかないので、4月データなどを足して試してみてください)

reshape2.pdf

5
5
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
5
5