r - How to avoid listing out function arguments but still subset too? -
i have function myfun(a,b,c,d,e,f,g,h) contains vectorised expression of parameters within it.
i'd add new column: data$result <- with(data, myfun(a,b,c,d,e,f,g,h)) a,b,c,d,e,f,g,h column names of data. i'm using data.table data.frame answers appreciated too.
so far parameter list (column names) can tedious type out, , i'd improve readability. there better way?
> myfun <- function(a,b,c) a+b+c > dt <- data.table(a=1:5,b=1:5,c=1:5) > with(dt,myfun(a,b,c)) [1] 3 6 9 12 15 the ultimate thing is:
dt[isflag, newcol:=myfun(a,b,c,d,e,f,g,h)] however:
> dt[a==1,do.call(myfun,dt)] [1] 3 6 9 12 15 notice j expression seems ignore subset. result should 3.
ignoring subset aspect now: df$result <- do.call("myfun", df). copies whole df whereas data.table allows add column reference: df[,result:=myfun(a,b,c,d,e,f,g,h)].
to include comment @eddi (and i'm not sure how combine these operations in data.frame easily) :
dt[isflag, newcol := do.call(myfun, .sd)] note .sd can used when aren't grouping, subsetting.
or if function literally adding arguments :
dt[isflag, newcol := do.call(sum, .sd)] this automatically places na newcol isflag false.
Comments
Post a Comment