本文へスキップ
からだにいいもの

Rのトピックスを中心に『まだ、まだ、知らない、役に立つ情報?』を発信します。

Rで解析:列名行名でデータを結合「flipTables」パッケージ

列や行方向,列名行名で結合するコマンドにはrbindやcbind,mergeがありますが、共通・非共通・全てを結合する場合には列名行名やデータサイズが異なる場合には工夫が必要です。

そんな工夫も必要なく、上記作業を手軽に実施できるパッケージの紹介です。Rの初心者だけでなく、玄人にもオススメです。

本パッケージの対象データはmatrixまたはarrayそしてvectorですが、data.frameの場合は一度「as.matrix」コマンドで変換後に操作することで操作が可能かと思います。

パッケージバージョンは2.9.6。実行コマンドはR version 4.2.2で確認しています。

パッケージのインストール

下記、コマンドを実行してください。

#パッケージのインストール
install.packages("devtools")
devtools::install_github("NumbersInternational/flipTables")
スポンサーリンク

実行コマンド

詳細はコメント、パッケージのヘルプを確認してください。

#パッケージの読み込み
library("flipTables")

###データ例の作成#####
#Data1の作成
Data1 <- matrix(1:16, nrow = 4, ncol = 4)
#行列名の付与
dimnames(Data1) <- list(c("あ", "い", "う", "え"), c("a", "b", "c", "d"))
#確認
Data1
   a b  c  d
あ 1 5  9 13
い 2 6 10 14
う 3 7 11 15
え 4 8 12 16
#Data2の作成
Data2 <- matrix(17:31, nrow = 5, ncol = 3)
#行列名の付与
dimnames(Data2) <- list(c("い", "か", "う", "き", "く"), c("b", "e", "c"))
#確認
Data2
  b  e  c
い 17 22 27
か 18 23 28
う 19 24 29
き 20 25 30
く 21 26 31
########

#結合コマンド:MergeTablesコマンド
#列名で判断:joinbyオプション;"Join rows"(行名の判断;"Join columns")
#条件:nonmatchingオプション;共通"Matching only"
MergeTables(Data1, Data2, joinby = "Join rows", nonmatching = "Matching only")
   b  c
あ    5  9
い.x  6 10
う.x  7 11
え    8 12
い.y 17 27
か   18 28
う.y 19 29
き   20 30
く   21 31

#条件:nonmatchingオプション;1番目のデータを優先"Keep all from first table"
MergeTables(Data1, Data2, joinby = "Join rows", nonmatching = "Keep all from first table")
   a  b  c  d
あ    1  5  9 13
い.x  2  6 10 14
う.x  3  7 11 15
え    4  8 12 16
い.y NA 17 27 NA
か   NA 18 28 NA
う.y NA 19 29 NA
き   NA 20 30 NA
く   NA 21 31 NA

#条件:nonmatchingオプション;2番目のデータを優先"Keep all from second table"
MergeTables(Data1, Data2, joinby = "Join rows", nonmatching = "Keep all from second table")
   b  c  e
あ    5  9 NA
い.x  6 10 NA
う.x  7 11 NA
え    8 12 NA
い.y 17 27 22
か   18 28 23
う.y 19 29 24
き   20 30 25
く   21 31 26

#条件:nonmatchingオプション;全てを結合"Keep all"
MergeTables(Data1, Data2, joinby = "Join rows", nonmatching = "Keep all")
   a  b  c  d  e
あ    1  5  9 13 NA
い.x  2  6 10 14 NA
う.x  3  7 11 15 NA
え    4  8 12 16 NA
い.y NA 17 27 NA 22
か   NA 18 28 NA 23
う.y NA 19 29 NA 24
き   NA 20 30 NA 25
く   NA 21 31 NA 26

少しでも、あなたの解析が楽になりますように!!

スポンサーリンク
Prices and shipping availability may change. Please refer to the product page at time of purchase.
Content displayed on this site is provided by Amazon and may be updated or removed.
Amazon Associate, karada-good earns income through qualifying sales.