2016-09-19 40 views
-1

我有兩個數據幀,一個是七行,另一個是兩行。這裏有兩個框架:在特定位置組合兩個不同長度的數據幀

   content ChatPosition 
1 This is a start line  START 
2 This is a middle line  MIDDLE 
3 This is a middle line  MIDDLE 
4 This is the last line   END 
5 This is a start line  START 
6 This is a middle line  MIDDLE 
7 This is the last line   END 

rating text_type 
1 0.2324 Postive 
2 0.8999 Postive 

基本上我想合併兩個數據幀,但我想將它們合併,從而在等級和text_type數據幀排隊的值第一個數據幀的第1行和第5行的值。換句話說,從DF2的值只能插在ChatPosition值=「START」,所以我想用一個數據幀,看起來像這樣結束了:

   content ChatPosition rating text_type 
1 This is a start line  START 0.2324 Postive 
2 This is a middle line  MIDDLE  NA  <NA> 
3 This is a middle line  MIDDLE  NA  <NA> 
4 This is the last line   END  NA  <NA> 
5 This is a start line  START 0.8999 Postive 
6 This is a middle line  MIDDLE  NA  <NA> 
7 This is the last line   END  NA  <NA> 

我有大約stackexchange一看,似乎有是一些與解決類似問題有關的問題和答案,其中OP沒有爲要合併的兩個幀指定特定的匹配標準。這裏有一些有用的代碼,但我無法擴展它來解決我的問題:

combining two data frames of different lengths

我已經包含下面的代碼來獲取兩個數據框填充。如果任何人可以幫助,將不勝感激。

content <- c("This is a start line" , "This is a middle line" , "This is a middle line" ,"This is the last line" , 
     "This is a start line" , "This is a middle line" , "This is the last line") 
ChatPosition <- c("START" , "MIDDLE" , "MIDDLE" , "END" , "START" ,"MIDDLE" , "END") 


df <- data.frame(content, ChatPosition) 
df 

rating <- c(0.2324, 0.8999) 
text_type <- c("Postive", "Postive") 
df2 <- data.frame(rating, text_type) 
df2 

回答

1

我想你可以通過創建空列,然後填充它們有條件

df3<- df 
df3 
df3$rating<- NA 
df3$text_type<- NA 

df3$rating[df3$ChatPosition=="START"]<- df2$rating 
df3$text_type[df3$ChatPosition=="START"]<- as.character(df2$text_type) 

df3 

編輯最容易做到這一點:在此我假設你想插入標記爲START

+0

謝謝R.S.這是一個很好的解決方案,因爲它不會假定ChatPosition ==「START」所在的行在哪裏。它只會根據match.Cheers插入。 Ĵ –

2

例如

row.names(df2) <- c(1,5) 
merge(df, df2, by="row.names", all.x=TRUE)[,-1] 
#     content ChatPosition rating text_type 
# 1 This is a start line  START 0.2324 Postive 
# 2 This is a middle line  MIDDLE  NA  <NA> 
# 3 This is a middle line  MIDDLE  NA  <NA> 
# 4 This is the last line   END  NA  <NA> 
# 5 This is a start line  START 0.8999 Postive 
# 6 This is a middle line  MIDDLE  NA  <NA> 
# 7 This is the last line   END  NA  <NA> 
+0

行的評級謝謝你的解決方案lukeA,行nam ES行預測瞭解我需要插入哪些行。我猜如果行位置發生變化,我會搜索哪些行需要插入。 –

相關問題