2016-07-26 102 views
0

我有兩個數據框在每一行中顯示一個月份和一個id列表。他們是這樣的:從data.frame中減去另一個data.frame中的列表中的列表

數據框答:

Month ID 
2016-03 1,2,3 
2016-04 4,5,6 
2016-05 7,8,9 

數據幀B:

Month ID 
2016-03 2,3,4 
2016-04 5,6,7 
2016-05 8,9,10 

看起來很簡單,也許我得太多了,但我無法減去相應的行來自數據幀A的數據幀B.

最終目標是在數據幀B被移除後從數據幀A獲得每行的ID的計數。

因此所產生的數據幀將如下所示:

Month ID 
2016-03 1 
2016-04 4 
2016-05 7 

和我的計數將在1, 1, 1

在此先感謝您的幫助!

更新:

在 「ID」 列中的值對象列表,如:

c("1", "2", "3")

+0

是你的'ID'列實際上'名單()''像列表(1,2,3)中的對象',或者他們只是字符串,比如' 「1,2,3」?提供'dput(A)'和'dput(B)'將會更好地知道。 – thelatemail

+0

他們是列表對象。 – phdj

+0

下面的答案是根據這個更新的。 – thelatemail

回答

2

使用setdiff一旦你爲每個Month合適的載體:

result <- Map(setdiff, A$ID, B$ID[match(A$Month,B$Month)])) 
#[[1]] 
#[1] 1 
# 
#[[2]] 
#[1] 4 
# 
#[[3]] 
#[1] 7 

如果你需要長度,你可以輕鬆做到:

lengths(result) 
#[1] 1 1 1 

其中,所使用的數據是:

A <- structure(list(Month = c("2016-03", "2016-04", "2016-05"), ID = list(
    c(1, 2, 3), c(4, 5, 6), c(7, 8, 9))), .Names = c("Month", 
"ID"), row.names = c(NA, -3L), class = "data.frame") 
B <- structure(list(Month = c("2016-03", "2016-04", "2016-05"), ID = list(
    c(2, 3, 4), c(5, 6, 7), c(8, 9, 10))), .Names = c("Month", 
"ID"), row.names = c(NA, -3L), class = "data.frame") 
相關問題