我有兩個資料集,我需要按 ID 值合并它們。問題是:
- ID 值可以在同一個資料集中重復(沒有其他唯一值可用)。
- 兩個資料集的行數或列數不相等。
例子:
df1
| ID | 性別 |
|---|---|
| 99 | 男性 |
| 85 | 女性 |
| 7 | 男性 |
df2
| ID | 體溫 | Body_Temperature_date_time |
|---|---|---|
| 99 | 36 | 2020 年 1 月 1 日上午 12:00 |
| 99 | 38 | 2020 年 2 月 1 日上午 10:30 |
| 99 | 37 | 2020 年 1 月 1 日上午 06:41 |
| 52 | 38 | 2020 年 1 月 2 日上午 11:00 |
| 11 | 39 | 2020 年 4 月 5 日晚上 9:09 |
| 7 | 35 | 2020 年 9 月 8 日凌晨 02:30 |
如何將這兩個資料集轉換為一個資料集,以便我以后可以在其上應用一些機器學習模型?
uj5u.com熱心網友回復:
根據您的預期結果,如果您想從每個資料框中回傳所有行,那么您可以使用full_joinfrom dplyr:
library(dplyr)
full_join(df2, df1, by = "ID")
或以 R 為基數:
merge(x=df2,y=df1,by="ID",all=TRUE)
輸出
ID Body_Temperature Body_Temperature_date_time Gender
1 99 36 1/1/2020 12:00 am Male
2 99 38 2/1/2020 10:30 am Male
3 99 37 1/1/2020 06:41 am Male
4 52 38 1/2/2020 11:00 am <NA>
5 11 39 4/5/2020 09:09 pm <NA>
6 7 35 9/8/2020 02:30 am Male
7 85 NA <NA> Female
如果要組合的資料框超過 2 個,且僅與ID列重疊,則可以reduce在資料框串列上使用(因此將要組合的所有資料框放入串列中):
library(tidyverse)
df_list <- list(df1, df2)
multi_full <- reduce(df_list, function(x, y, ...)
full_join(x, y, by = "ID", ...))
或Reduce以 R 為基數:
df_list <- list(df1, df2)
multi_full <- Reduce(function(x, y, ...)
merge(x, y, by = "ID", all = TRUE, ...), df_list)
資料
df1 <- structure(list(ID = c(99L, 85L, 7L), Gender = c("Male", "Female",
"Male")), class = "data.frame", row.names = c(NA, -3L))
df2 <- structure(list(ID = c(99L, 99L, 99L, 52L, 11L, 7L), Body_Temperature = c(36L,
38L, 37L, 38L, 39L, 35L), Body_Temperature_date_time = c("1/1/2020 12:00 am",
"2/1/2020 10:30 am", "1/1/2020 06:41 am", "1/2/2020 11:00 am",
"4/5/2020 09:09 pm", "9/8/2020 02:30 am")), class = "data.frame", row.names = c(NA,
-6L))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/483336.html
上一篇:合并沒有對應ID的資料幀
下一篇:sql中的多個連接中的索引
