r - Using the apply or plyr when the return has a variable number of columns -


i'm wondering if there way directly return data frame apply or plyr call when return function can have variable number of columns (but have same number of rows). example:

df <- data.frame(a = 1:3, b = c("a","b", "c"))  my_fun <- function(x){   if(is.numeric(unlist(x))){     return(x)   } else {     return(cbind(x, x))   } } 

the closest i've been able returning list , converting data frame:

library(plyr) data.frame(alply(df, 2, my_fun)) ##   x2.b x2.b.1 ## 1 1         ## 2 2    b      b ## 3 3    c      c 

it feels there should way without conversion, there?

i use lapply() lot in way, when want apply function several columns of data frame. in base r, can treat data frame list, each column 1 element. if use lapply() usual return list, isn't want.

> lapply(df, my_fun) $a [1] 1 2 3  $b      x x [1,] 1 1 [2,] 2 2 [3,] 3 3 

but if assign result df[] signal r want subset of original data frame (the full subset, isn't subset @ all), preserving data frame object type.

> df[] <- lapply(df, my_fun) > df   b.x b.x 1 1   1   1 2 2   2   2 3 3   3   3 

Comments