R-列名が同じで順序が異なる2つのデータフレームを組み合わせる方法

2020-07-11 r dataframe sorting merge

2つのデータフレームを結合したいのですが、順序が異なり、一部の列がRRで欠落しています。

次に例を示します。

 df.1 <- data.frame(class = c(1,6,8,9,7,8,9,6,4), math = c(0.7, 0.4, 0.7), hist = c(0.6, 0.4, 0.3), geom = c(0.7, 0.4, 0.7), eng = c(0.7, 0.4, 0.7), draw = c(0.8, 0.6, 0.7)) df.2 <- data.frame(eng = c(0.7, 0.4, 0.7, class = c(2, 1, 2, 3, 1),draw = c(0.8, 0.6, 0.7),geom = c(0.7, 0.4, 0.7) ) 
 
 df.1 <- data.frame(class = c(1,6,8,9,7,8,9,6,4), math = c(0.7, 0.4, 0.7), hist = c(0.6, 0.4, 0.3), geom = c(0.7, 0.4, 0.7), eng = c(0.7, 0.4, 0.7), draw = c(0.8, 0.6, 0.7)) df.2 <- data.frame(eng = c(0.7, 0.4, 0.7, class = c(2, 1, 2, 3, 1),draw = c(0.8, 0.6, 0.7),geom = c(0.7, 0.4, 0.7) ) 
 

ありがとうございました

Answers

これはあなたが探しているものですか?

library(dplyr)

df <- 
  full_join(df.1, df.2)
#> Joining, by = c("class", "geom", "eng", "draw")

df
#>    class math hist geom eng draw
#> 1      1  0.7  0.6  0.7 0.7  0.8
#> 2      6  0.4  0.4  0.4 0.4  0.6
#> 3      8  0.7  0.3  0.7 0.7  0.7
#> 4      9  0.7  0.6  0.7 0.7  0.8
#> 5      7  0.4  0.4  0.4 0.4  0.6
#> 6      8  0.7  0.3  0.7 0.7  0.7
#> 7      9  0.7  0.6  0.7 0.7  0.8
#> 8      6  0.4  0.4  0.4 0.4  0.6
#> 9      4  0.7  0.3  0.7 0.7  0.7
#> 10     2   NA   NA  0.7 0.7  0.8
#> 11     1   NA   NA  0.4 0.4  0.6
#> 12     2   NA   NA  0.7 0.7  0.7
#> 13     3   NA   NA  0.7 0.7  0.8
#> 14     1   NA   NA  0.4 0.4  0.6
#> 15     3   NA   NA  0.7 0.7  0.7

reprexパッケージ (v0.3.0)によって2020-07-11に作成されました

データ

df.1 <- data.frame(class = c(1,6,8,9,7,8,9,6,4), 
                   math = c(0.7, 0.4, 0.7), 
                   hist = c(0.6, 0.4, 0.3), 
                   geom = c(0.7, 0.4, 0.7), 
                   eng = c(0.7, 0.4, 0.7), 
                   draw = c(0.8, 0.6, 0.7))

df.2 <- data.frame(eng = c(0.7, 0.4, 0.7), 
                   class = c(2, 1, 2, 3, 1, 3),
                   draw = c(0.8, 0.6, 0.7),
                   geom = c(0.7, 0.4, 0.7) )

以下は私が得ることができるすべてです

class = c(1, 6, 8, 9, 7, 8, 9, 6, 4)
math = c(0.7, 0.4, 0.7)
hist = c(0.6, 0.4, 0.3)
geom = c(0.7, 0.4, 0.7)
eng = c(0.7, 0.4, 0.7)
draw = c(0.8, 0.6, 0.7)

dimension <-
  seq(max(
    length(class),
    length(math),
    length(hist),
    length(geom),
    length(eng),
    length(draw)
  ))

df.new <- data.frame(class[dimension], math[dimension], hist[dimension], 
                     geom[dimension], eng[dimension], draw[dimension])

names(df.new) <- c('class', 'math', 'hist', 'geom', 'eng', 'draw')

出力

df.new
  class math hist geom eng draw
1     1  0.7  0.6  0.7 0.7  0.8
2     6  0.4  0.4  0.4 0.4  0.6
3     8  0.7  0.3  0.7 0.7  0.7
4     9   NA   NA   NA  NA   NA
5     7   NA   NA   NA  NA   NA
6     8   NA   NA   NA  NA   NA
7     9   NA   NA   NA  NA   NA
8     6   NA   NA   NA  NA   NA
9     4   NA   NA   NA  NA   NA

Related