2013-02-15 8 views
5

Dopo this post, ho un'altra domanda sulle colonne di elenchi in data.table.Come posso digitare una colonna di elenchi in data.table

DT = data.table(x=list(c(1,2),c(1,2),c(3,4,5))) 

Sembra che non sia possibile digitare una colonna di elenchi.

DT[,y:=.I,by=x] 
Erreur dans `[.data.table`(DT, , `:=`(y, .I), by = x) : 
    The items in the 'by' or 'keyby' list are length (2,2,3). Each must be same length as rows in x or number of rows returned by i (3). 

ho pensato che avrei potuto con le liste di uguale lunghezza, ma:

DT = data.table(x=list(c(1,2),c(1,2),c(3,5))) 
DT[,y:=.I,by=x] 
Erreur dans `[.data.table`(DT, , `:=`(y, .I), by = x) : 
    The items in the 'by' or 'keyby' list are length (2,2,2). Each must be same length as rows in x or number of rows returned by i (3). 

C'è una soluzione? Se no, che ne pensi di una richiesta di funzionalità?

+0

sì, 'list' non è consentito (attualmente) come colonna chiave. Si ottiene questo messaggio quando si esegue 'setkey (DT," x ") – Arun

risposta

3

farei qualcosa di simile a questo come una soluzione alternativa:

DT[, y := which(DT$x %in% x), by = 1:nrow(DT)] 

Questo restituisce il primo indice corrispondente sempre, che servirà come un id di gruppo.

si dovrebbe fare qualcosa di simile:

DT[, psnInGrp := seq_along(x), by=y] 

#  x y psnInGrp 
# 1: 1,2 1  1 
# 2: 1,2 1  2 
# 3: 3,4,5 3  1 
+1

Doh ... tempo per il caffè ... – statquant

+0

Non sono sicuro di' by = 1: nrow (DT) 'in generale. Può essere più veloce usare 'lapply' e gli amici in' j'. –

+0

@MatthewDowle, è possibile selezionare una riga per riga senza eseguire '1: nrow (DT)'? – Arun

Problemi correlati