2016-03-02 23 views
1

我想要從數據框中的每個記錄,其中每個記錄的前3個屬性等於來自另一個數據框中的記錄的相同3個屬性。R - 在不同的數據框中的類似記錄

例如,我有:

File, Paragraph, Sentence, E, ED 
    1.txt, 1, 1, CM, C.M. 
    1.txt, 1, 1, LF, L.F. 
    1.txt, 2, 1, E, E. 
    1.txt, 2, 1, M, M. 
    1.txt, 4, 1, LF, L.F. 
    1.txt, 4, 1, NM, N.M. 
    1.txt, 6, 1, RN, R.N. 
    1.txt, 7, 1, AO, A.O. 

我有3分公共列此數據幀,但較少線。

File Paragraph Sentence occurrences 
    1.txt  1  1   2 
    1.txt  2  1   2 
    1.txt  4  1   2 

它想獲得這樣的事:

File, Paragraph, Sentence, E, ED 
    1.txt, 1, 1, CM, C.M. 
    1.txt, 1, 1, LF, L.F. 
    1.txt, 2, 1, E, E. 
    1.txt, 2, 1, M, M. 
    1.txt, 4, 1, LF, L.F. 
    1.txt, 4, 1, NM, N.M. 

我怎樣纔能有效地做到這一點?

回答

0

嘗試使用合併。類似的東西:

merge(x = first_data_frame, y = second_data_frame) 

這將它們合併,基本上喜歡加入SQL(發現路口),並應只保留具有相同的文件,段落,句子記錄。然後你可以拿出額外的列「出現」。你可以閱讀更多合併here。 您可以通過列控制通過合併:

merge(x = first_data_frame, y = second_data_frame, by=c("File", "Paragraph", "Sentence")) 
+0

謝謝。你的建議解決了我的問題。 –

+0

在我已經嘗試使用'merge()',但沒有參數'by'之前。 –

1

只要使用subset()%in%運營商。

subset(df, Paragraph %in% df1$Paragraph) # Assuming Paragraph is numeric in both 
# File Paragraph Sentence E. ED 
#1 1.txt,   1  1, CM, C.M. 
#2 1.txt,   1  1, LF, L.F. 
#3 1.txt,   2  1, E, E. 
#4 1.txt,   2  1, M, M. 
#5 1.txt,   4  1, LF, L.F. 
#6 1.txt,   4  1, NM, N.M. 
+0

當然數據幀是樣本。所以我有文件,段落和句子的不同組合。 我嘗試過'子集(df,%df1中的文件%$%df1 $文件和段落%$段落&句子%%df1 $句子)'但沒有成功。 但我不知道是否可以使用'subset()'。我可以像@Zakkery建議的那樣用'merge()'來獲得它。 –

相關問題