簡體   English   中英

列字符串的唯一組合的子集

[英]subsetting on unique combination of column strings

在較大數據集的最后日期,我有關於表現最佳的數據。 接下來,我想對整個數據集進行子集化,以檢索那些表現最好的數據。 “最佳表演者”是兩個字符串的組合。 但是,到目前為止,我還不能正確地對數據進行子集化。

我嘗試使用%in%來完成部分工作,但它包括具有一個或另一個字符串變量的所有行,而不是兩者的唯一組合。

library(data.table)
best = data.table(Date = as.Date(c("2016-01-01", "2016-01-01")), x = c("a", "b"), y = c("p", "q"))
wholedt = data.table(Date = as.Date(c("2015-12-01","2015-12-01","2015-12-01","2016-01-01", "2016-01-01", "2016-01-01")), x = c("a", "c", "b", "a","a", "b"), y = c("p", "q", "q", "q","p", "q"))
SDbest_of_whole = wholedt[with(wholedt, x %in% best$x & y %in% best$y)]

預期輸出將包括(a,p)和(b,q)組合的所有數據點。 沒有(a,q)或(b,p)的組合

expected_output = data.table(Date = as.Date(c("2015-12-01","2015-12-01","2016-01-01", "2016-01-01")), x = c("a", "b","a", "b"), y = c("p", "q","p", "q"))
> expected_output
     Date x y
1: 2015-12-01 a p
2: 2015-12-01 b q
3: 2016-01-01 a p
4: 2016-01-01 b q

確保僅使用感興趣的組合的一種方法是merge數據集:

library(data.table)
best = data.table(Date = as.Date(c("2016-01-01", "2016-01-01")), x = c("a", "b"), y = c("p", "q"))
wholedt = data.table(Date = as.Date(c("2015-12-01","2015-12-01","2015-12-01","2016-01-01", "2016-01-01", "2016-01-01")), x = c("a", "c", "b", "a","a", "b"), y = c("p", "q", "q", "q","p", "q"))

best[,Date:=NULL]
merge(best, wholedt)

#    x y       Date
# 1: a p 2015-12-01
# 2: a p 2016-01-01
# 3: b q 2015-12-01
# 4: b q 2016-01-01

對於wholedt每一行,您要比較是否有best行是相同的。

SDbest_of_whole <- wholedt[apply(wholedt[,c('x', 'y')], 1, function(w) any(apply(best[,c('x', 'y')], 1, identical, w))),]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM