Search code examples
rlistdynamiclookupdynamic-columns

Dynamically concatenate Columns in R


I'm having a problem dynamically concatenating Columns. I'm building a Regional Calculator which sums measures but want it to be flexible enough to accommodate various inputs.

Using mtcars and an example:

                ColA <- "mpg"
                ColB <- "cyl"
                ColC <- "disp"

mtcars$lookup <-paste0(mtcars[[ColA]],mtcars[[ColB]],mtcars[[ColC]])

(I know the above example concatenates Numbers which doesn't make sense! - in my version columns containing strings are used)

This would give me the lookup column that I need. However what I'd like to do is populate my lookup column dynamically. Sometimes there will be 2 columns, sometimes they may be 5 columns and the Column Names will change from one project to the next.

I'm thinking I could populate the strings in ColA > ColX using a List and a For Loop. But I'm not sure how to dynamically solve the lookup creation using paste0....

mtcars$lookup <-paste0(mtcars[[ColA]],......mtcars[[ColX]])

Any ideas how to solve this problem? Thanks!


Solution

  • You can use the do.call(paste0, ...) idiom:

    mtcars$lookup <- do.call(paste0, mtcars[c(ColA, ColB, ColC)])
    mtcars$lookup
    ##  [1] "216160"     "216160"     "22.84108"   "21.46258"   "18.78360"   "18.16225"   "14.38360"  
    ##  [8] "24.44146.7" "22.84140.8" "19.26167.6" "17.86167.6" "16.48275.8" "17.38275.8" "15.28275.8"
    ## [15] "10.48472"   "10.48460"   "14.78440"   "32.4478.7"  "30.4475.7"  "33.9471.1"  "21.54120.1"
    ## [22] "15.58318"   "15.28304"   "13.38350"   "19.28400"   "27.3479"    "264120.3"   "30.4495.1" 
    ## [29] "15.88351"   "19.76145"   "158301"     "21.44121"  
    

    Replace c(ColA, ColB, ColC) with a vector of the column names or even the column positions.


    In the "tidyverse", you can also use unite. Try the following to see what it does:

    library(tidyverse) ## `unite` comes from the tidyr package, FYI
    mtcars %>% unite(output, mpg, cyl, disp, sep = "")