2016-03-07 62 views
2

我有一個data.table與多個列。其中一列目前用作'鑰匙'(例如keyb)。另一列(比如說A)可能有或沒有數據。我想提供一個向量,每個鍵隨機抽樣兩行,如果這個鍵出現在向量中,其中1行包含A中的數據,而另一行則不包含。不同條件的示例data.table行

MRE:

#data.table 
trys <- structure(list(keyb = c("x", "x", "x", "x", "x", "y", "y", "y", 
"y", "y"), A = c("1", "", "1", "", "", "1", "", "", "1", "")), .Names = c("keyb", 
"A"), row.names = c(NA, -10L), class = c("data.table", "data.frame" 
)) 
setkey(trys,keyb) 

#list with keys 
list_try <- structure(list(a = "x", b = c("r", "y","x")), .Names = c("a", "b")) 

我可以,比如子集data.table基於出現在list_try的元素:

trys[keyb %in% list_try[[2]]] 

我原來的(也可能是低效的想法),是試圖將每個鍵鏈接兩行樣本,其中A列包含數據或不包含數據,然後進行合併。但它不工作:

#here I was trying to sample rows based on whether A has data or not 
#here for rows where A has no data 
trys[keyb %in% list_try[[2]]][nchar(A)==0][sample(.N, 2), ,by = keyb] 
#here for rows where A has data 
trys[keyb %in% list_try[[2]]][nchar(A)==1][sample(.N, 2), ,by = keyb] 

在這種情況下,我的預期產出將有兩個data.tables(一個用於a,一個用於blist_try),每個元素出現兩行:所以data.table從a將有兩行(一個有和沒有數據在A),並從b,四行(兩個有兩個沒有數據在A)。

請讓我知道,如果我可以讓這篇文章更清楚

+1

不知道,但也許這'改掉[list_try [[2]],nomatch = 0L,sample(.I,1L),by =。(keyb,A)]'? 'V1'是採樣行索引 –

+1

對於兩個數據集,可能是'lapply(list_try,function(x)trys [x,nomatch = 0L,sample(.I,1L),by =。(keyb,A)]) ' –

+0

@DavidArenburg這是爲我的示例數據集工作,我會調整我的實際數據集的評論。它將刪除所有其他列(包含相關信息),出於某種原因,它給了我一個包含數據的列的兩行樣本,而不是1 – erasmortg

回答

1

你可以添加Aby聲明過,而通過修改A != ""其轉換成二進制向量,與二進制相結合加入(同時加入nomatch = 0L爲了從原始數據中移除非比賽),你可以然後從行索引.I由這兩個聚合樣品中,然後子集設置

對於單個子集的情況下

trys[trys[list_try[[2]], nomatch = 0L, sample(.I, 1L), by = .(keyb, A != "")]$V1] 
# keyb A 
# 1: y 1 
# 2: y 
# 3: x 1 
# 4: x 

對於更一般的情況下,當你想根據密鑰列表創建單獨的數據集,你可以很容易地嵌入到這個lapply

lapply(list_try, 
     function(x) trys[trys[x, nomatch = 0L, sample(.I, 1L), by = .(keyb, A != "")]$V1]) 
# $a 
# keyb A 
# 1: x 1 
# 2: x 
# 
# $b 
# keyb A 
# 1: y 1 
# 2: y 
# 3: x 1 
# 4: x