【R】行或列數目不同的兩個數據框如何用rbind/cbind合並?


前言

通常我們用rbind和cbind合並相同行列的數據框。當兩個數據框具有不同行列數目時,直接用會報錯。

> df1 <- data.frame(a = c(1:5), c = c(6:10));df1
  a  c
1 1  6
2 2  7
3 3  8
4 4  9
5 5 10
> df2 <- data.frame(a = c(11:15), b = c(16:20));df2
   a  b
1 11 16
2 12 17
3 13 18
4 14 19
5 15 20
> rbind(df1,df2)
Error in match.names(clabs, names(xi)) : 名字同原來已有的名字不相對

rbind/cbind對於行列名稱一定要相同,順序可不同,例如:

> df1 <- data.frame(b = c(1:5), a = c(6:10));df1
  b  a
1 1  6
2 2  7
3 3  8
4 4  9
5 5 10
> df2 <- data.frame(a = c(11:15), b = c(16:20));df2
   a  b
1 11 16
2 12 17
3 13 18
4 14 19
5 15 20
> rbind(df1,df2)
    b  a
1   1  6
2   2  7
3   3  8
4   4  9
5   5 10
6  16 11
7  17 12
8  18 13
9  19 14
10 20 15

那么怎么強行合並,即相同部分合並,不同部分用NA取代?

方法一:dplyr的bind_rows

> df1 <- data.frame(b = c(1:5), a = c(6:10));df1
  b  a
1 1  6
2 2  7
3 3  8
4 4  9
5 5 10
> df2 <- data.frame(a = c(11:15), b = c(16:20), c = LETTERS[1:5]);df2
   a  b c
1 11 16 A
2 12 17 B
3 13 18 C
4 14 19 D
5 15 20 E
> dplyr::bind_rows(df1, df2)
    b  a    c
1   1  6 <NA>
2   2  7 <NA>
3   3  8 <NA>
4   4  9 <NA>
5   5 10 <NA>
6  16 11    A
7  17 12    B
8  18 13    C
9  19 14    D
10 20 15    E

方法二:plyr的rbind.fill

> plyr::rbind.fill(df1,df2)
    b  a    c
1   1  6 <NA>
2   2  7 <NA>
3   3  8 <NA>
4   4  9 <NA>
5   5 10 <NA>
6  16 11    A
7  17 12    B
8  18 13    C
9  19 14    D
10 20 15    E

可以看到,行列名可以不同,順序和rbind一樣,無關緊要。但最好還是相同順序吧。

https://stackoverflow.com/questions/3402371/combine-two-data-frames-by-rows-rbind-when-they-have-different-sets-of-columns


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM