2015-09-30 27 views
2

數據

我有2個數據幀如下:如何在R中組合兩個數據幀(請參閱詳細信息)?

df <- data.frame(frames = 1:10, 
       X1 = c(0,0,0,10,10,10,10,15,15,15), 
       X2 = c(0,0,0,15,15,15,15,10,10,10), 
       X3 = rep(0,10), 
       X4 = rep(0,10), 
       X5 = rep(0,10)) 


frames =時間幀數
X1, X2, ..., X5包含車輛的唯一標識號。在任何時間框架,X1最靠近給用戶(駕駛模擬器中的駕駛員),X2是**第二近用戶**,依此類推。例如,在frames 5處,車輛#10距離最近,所以在X1中,並且車輛#15是第二近的。用戶周圍沒有其他車輛,因此列X3X5包含零。

請注意:df沒有位置;它具有車輛識別號碼。所以0代表沒有車輛,10和15代表車輛ID10和ID15。它們不是一個序列,數字沒有意義,所以10不是10英尺或第十輛車,它只是一個ID。我更喜歡A,B,...但我以ID號的格式獲取數據。是的,我想把0作爲NAs。

第二數據幀具有類似的結構,但包含所述車輛的速度,而不是標識:

df1 <- data.frame(frames = 1:10, 
       X1 = c(0.00,0.00,0.00,14.53,14.90,14.73,14.60,13.90,14.10,14.90), 
       X2 = c(0.00,0.00,0.00,12.57,12.80,13.10,13.60,14.65,14.70,14.79), 
       X3 = rep(0.00,10), 
       X4 = rep(0.00,10), 
       X5 = rep(0.00,10)) 

實施例:在frames 5,車輛#10的速度爲14.90米/ s以及車輛#的15是12.80米/秒。

我想幹什麼?

我想這2個數據幀結合起來,創造一個新的,看起來像這樣:

> df.final 
    ID frames speed 
1 10  4 14.53 
2 10  5 14.90 
3 10  6 14.73 
4 10  7 14.60 
5 10  8 14.65 
6 10  9 14.70 
7 10  10 14.79 
8 15  4 12.57 
9 15  5 12.80 
10 15  6 13.10 
11 15  7 13.60 
12 15  8 13.90 
13 15  9 14.10 
14 15  10 14.90 

我怎樣才能做到這一點?我已閱讀tidyr包的教程,但仍然無法弄清楚如何做tidyr

+0

只是爲了澄清,似乎儘管您的初始數據框「df」和「df1」被設置爲提供有關每輛車相對於駕駛員的位置的一些信息,但在最終數據框中,您對此信息不感興趣嗎?另外,您想將車輛ID或速度變量中的0作爲NA來處理,對嗎? – tsurudak

+0

@tsurudak感謝您的回覆。 'df'沒有位置;它具有車輛識別號碼。所以0表示沒有車輛,10和15是車輛ID 10和ID 15.它們不是一個序列。是的,我想把0作爲NAs。 –

回答

4

利用和dplyr你可以做

library(tidyr) 
library(dplyr) 

## 'melt' the dataframes into long format 
## here, 'gather' is the tidyr equivalent of reshape2::melt 
df <- df %>% 
    gather(position, car_id, X1:X5) 

df1 <- df1 %>% 
    gather(position, speed, X1:X5) 

## merge (join) by frames and position 
df_final <- merge(df, df1, by=c("frames", "position")) 

## Alternatively you can used dplyr::inner_join 
## df_final <- inner_join(df, df1, by=c("frames","position")) 
## although you don't need the 'by' argument here as inner_join 
## detects the common/join columns 

## filter and sort the results 
df_final <- df_final %>% 
    filter(car_id != 0) %>% 
    arrange(car_id, frames) 

這給

df_final 
    frames position car_id speed 
1  4  X1  10 14.53 
2  5  X1  10 14.90 
3  6  X1  10 14.73 
4  7  X1  10 14.60 
.... 
+0

非常感謝! –

相關問題