[R] concatenating columns in data.frame

Bert Gunter bgunter@4567 @end|ng |rom gm@||@com
Thu Jul 1 20:24:59 CEST 2021


Why not simply:

## reprex
set.seed(123)
df = data.frame("A"=sample(letters, 10), "B"=sample(letters, 10),
                "C"=sample(letters,10), "D"=sample(letters, 10))
df
use_columns = c("D", "B")

## one liner
df$combo_col <- do.call(paste,c(df[,use_columns], sep = "_"))
df

In case you are wondering, this works because by definition *a date
frame **is** a list*, so the concatenation is list concatenation.


Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )

Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )


On Thu, Jul 1, 2021 at 7:37 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))
>
>
> Thanks
>
>
> --
> Micha Silver
> Ben Gurion Univ.
> Sde Boker, Remote Sensing Lab
> cell: +972-523-665918
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list