Search code examples
rlistcbinddo.call

Bind vector with list of vectors using cbind


I have an original data.frame and I would like to run lapply on certain columns then cbind the remaining columns with the results from the lapply operation.

See code below. I would ideally like b to contain the first id column from the data.frame with the results from the lapply. I am assuming my error is that my list argument to cbind contains a list of lists...the first argument to list is a vector, which could be handled, but the second argument is an actual list itself. Just wondering how to handle this.

Thanks!

df <- data.frame(id = 1:10,
                 colB = 11:20,
                 colC = 21:30)

a <- lapply(df[,2:3],
            function(x) {x = 10 * x}
)

b <- do.call(cbind,
             list(df[,1],
                  a))

Created on 2019-02-16 by the reprex package (v0.2.0).


Solution

  • The difference is subtle but important: for your code to work the way you want it you need

    b <- do.call(cbind, list(df[1], a))
    #                        ^^^^^
    

    Result

    b
    #   id colB colC
    #1   1  110  210
    #2   2  120  220
    #3   3  130  230
    #4   4  140  240
    #5   5  150  250
    #6   6  160  260
    #7   7  170  270
    #8   8  180  280
    #9   9  190  290
    #10 10  200  300
    

    The difference is that df[1] returns a data.frame while df[,1] returns a vector. cbind has a method for data.frames which is what get's called in above case, but not in your case.