I want to list unique IDs within groups, where the grouping variable can be selected by the user. The following works:
if(useGroupVar1){
dt[,unique(id),.(group1a,group1b,group1c)]
} else {
dt[,unique(id),group2]
}
The expressions I'm using in my code to filter rows are actually fairly long so I want to avoid duplicating code. I came up with this "solution", which doesn't actually work:
dt[,unique(id),if(useGroupVar1){.(group1a,group1b,group1c)}else{group2}]
If the condition leads to using group2 alone, it works (though the column is called if), but trying to get it to use .(group1a,group1b,group1c) results in
Error in eval(expr, envir, enclos) : could not find function "."
Now, I read .() is an alias to list(), so using the latter gets me this
Error in bysubl[[jj + 1L]] : subscript out of bounds
Is there a way to implement a conditional by without duplicating entire expressions?
by = if (useGroupVar1) paste0('group1', c('a','b','c')) else 'group2')- MichaelChiricoError in `[.data.table`(tabla, if (identical(codificacion[[1]][i]$codCIE, : 'by' appears to evaluate to column names but isn't c() or key(). Use by=list(...) if you can. Otherwise, by=eval(if (!porEESS) { c("cod_dpto", "cod_prov", "cod_dist")} else { cod_2000}) should work. This is for efficiency so data.table can detect which columns are needed.- overdisperse[call:group_var = if (...) else. Thendt[ , , by = group_var]. - MichaelChirico