[R] concatenating columns in data.frame

Eric Berger
Thu, 01 Jul 2021 15:30:45 -0000

You can do the same steps but without so much intermediate saving to
shorten it

f <- function(x) {
  do.call(rbind,lapply(1:nrow(x),
                       function(r) {paste(x[r,], collapse="_")}))
}

df_combo <- cbind(df,Combo=f(df[,c(4,2)]))

HTH,
Eric


On Thu, Jul 1, 2021 at 5:37 PM Micha Silver <tsvibar at 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 at 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.
>

	[[alternative HTML version deleted]]