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

I am wondering if there is a way to directly return a data frame from a call, applyor plyrwhen returning from a function can have a variable number of columns (but will always have the same number of rows). For 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 could get by returning the list and converting it to a data frame:

library(plyr)
data.frame(alply(df, 2, my_fun))
##   A X2.B X2.B.1
## 1 1    a      a
## 2 2    b      b
## 3 3    c      c

It seems like there should be a way to do this without additional conversion, is there?

+4
source share
1 answer

lapply() , . R , . lapply(), , , .

> lapply(df, my_fun)
$A
[1] 1 2 3

$B
     x x
[1,] 1 1
[2,] 2 2
[3,] 3 3

df[], R, ( , ), .

> df[] <- lapply(df, my_fun)
> df
  A B.x B.x
1 1   1   1
2 2   2   2
3 3   3   3
+4

Source: https://habr.com/ru/post/1626478/


All Articles