Search code examples
rmultiple-columnscoalesce

Creating multiple columns in one line of code where each column is created by coalescing different columns


How can I create multiple columns in just a line of code? For instance, in the picture below, I am trying make the below six lines of code into a single line of code?

A1AFirstBatch4$OOATB1 <- with(A1AFirstBatch4, coalesce(Q1a, Q1b)) 
A1AFirstBatch4$OOATB2 <- with(A1AFirstBatch4, coalesce(Q2a, Q2b)) 
A1AFirstBatch4$OOATB3 <- with(A1AFirstBatch4, coalesce(Q3a, Q3b)) 
A1AFirstBatch4$OOATB4 <- with(A1AFirstBatch4, coalesce(Q4a, Q4b)) 
A1AFirstBatch4$OOATB5 <- with(A1AFirstBatch4, coalesce(Q5a, Q5b)) 
A1AFirstBatch4$OOATB6 <- with(A1AFirstBatch4, coalesce(Q6a, Q6b)) 

Created on 2021-04-07 by the reprex package (v2.0.0)


Solution

  • You could create the dataframe like this. In case you need to append (not create), an option would be to merge a newly created dataframe with the old one afterwards.
    If it is really ONE LINE (not one statement) you are looking for, you can omit the linebreaks inserted here to increase the ability to read it.

    A1AFirstBatch4 <- data.frame(OOATB1 = coalesce(Q1a, Q1b),
                                 OOATB2 = coalesce(Q2a, Q2b),
                                 ... and so forth ... )
    

    Is this what you are looking for? I am not sure what you need to achieve.

    In case it is a piece of code for a function, if-statement etc.: use curly brackets:

    {statement 1
    statement 2
    statement 3...
    }
    

    (taking your question literally, one could simply put semicolons in between statements in a single line, but this is unreadable and I am not sure about the max char per line A... <- ....; A... <- ....; ...).