[R] concatenating columns in data.frame

Berry, Charles ccberry @end|ng |rom he@|th@uc@d@edu
Thu Jul 1 20:02:38 CEST 2021



> On Jul 1, 2021, at 7:36 AM, Micha Silver <tsvibar using gmail.com> wrote:
> 
> I need to create a new data.frame column as a concatenation of existing character columns. But the number and name of the columns to concatenate needs to be passed in dynamically. The code below does what I want, but seems very clumsy. Any suggestions how to improve?
> 
> 
> df = data.frame("A"=sample(letters, 10), "B"=sample(letters, 10), "C"=sample(letters,10), "D"=sample(letters, 10))
> 
> # Which columns to concat:
> 
> use_columns = c("D", "B")
> 
> 
> UpdateCombo = function(df, use_columns) {
>     use_df = df[, use_columns]
>     combo_list = lapply(1:nrow(use_df), function(r) {
>     r_combo = paste(use_df[r,], collapse="_")
>     return(data.frame("Combo" = r_combo))
>     })
>     combo = do.call(rbind, combo_list)
> 
>     names(combo) = "Combo"
> 
>     return(combo)
> 
> }
> 
> 
> combo_col = UpdateCombo(df, use_columns)
> 
> df_combo = do.call(cbind, list(df, combo_col))
> 
> 


I'd do this:


UpdateCombo <-
  function(df, use_columns){
    pasteUnder <- function(...) paste(..., sep="_")
    do.call(pasteUnder, df[, use_columns])
  }

df_combo <- cbind(df, Combo=UpdateCombo(df, use_columns))

HTH,
Chuck



More information about the R-help mailing list