Ho un oggetto data.table
che contiene più colonne che specificano casi univoci. Nel piccolo esempio seguente, le variabili "name
", "job
" e "sex
" specificano gli ID univoci. Vorrei aggiungere righe mancanti in modo che ogni caso abbia una riga per ogni possibile istanza di un'altra variabile, "from
" (simile a expand.grid
).Aggiungere righe mancanti a data.table in base a più colonne con chiave
library(data.table)
set.seed(1)
mydata <- data.table(name = c("john","john","john","john","mary","chris","chris","chris"),
job = c("teacher","teacher","teacher","teacher","police","lawyer","lawyer","doctor"),
sex = c("male","male","male","male","female","female","male","male"),
from = c("NYT","USAT","BG","TIME","USAT","BG","NYT","NYT"),
score = rnorm(8))
setkeyv(mydata, cols=c("name","job","sex"))
mydata[CJ(unique(name, job, sex), unique(from))]
Ecco l'attuale oggetto data.table:
> mydata
name job sex from score
1: john teacher male NYT -0.6264538
2: john teacher male USAT 0.1836433
3: john teacher male BG -0.8356286
4: john teacher male TIME 1.5952808
5: mary police female USAT 0.3295078
6: chris lawyer female BG -0.8204684
7: chris lawyer male NYT 0.4874291
8: chris doctor male NYT 0.7383247
Ecco il risultato che vorrei:
> mydata
name job sex from score
1: john teacher male NYT -0.6264538
2: john teacher male USAT 0.1836433
3: john teacher male BG -0.8356286
4: john teacher male TIME 1.5952808
5: mary police female NYT NA
6: mary police female USAT 0.3295078
7: mary police female BG NA
8: mary police female TIME NA
9: chris lawyer female NYT -NA
10: chris lawyer female USAT -NA
11: chris lawyer female BG -0.8204684
12: chris lawyer female TIME -NA
13: chris lawyer male NYT 0.4874291
14: chris lawyer male USAT NA
15: chris lawyer male BG NA
16: chris lawyer male TIME NA
17: chris doctor male NYT 0.7383247
18: chris doctor male USAT NA
19: chris doctor male BG NA
20: chris doctor male TIME NA
Ecco che cosa ho provato:
setkeyv(mydata, cols=c("name","job","sex"))
mydata[CJ(unique(name, job, sex), unique(from))]
Ma ricevo il seguente errore e aggiungo fromLast = T RUE (o FALSO) non mi dà la giusta soluzione:
Error in unique.default(name, job, sex) :
'fromLast' must be TRUE or FALSE
Ecco le relative risposte che ho incontrato (ma nessuno sembra occuparsi di più colonne a chiave): add missing rows to a data table
Efficiently inserting default missing rows in a data.table
Fastest way to add rows for missing values in a data.frame?
Abbastanza intenso. È 2: 4 per la selezione delle colonne? – jazzurro
@jazzurro Sì, per rinominare quelle colonne usando 'setnames' – akrun
Capito. Grazie mille. :) – jazzurro