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@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.

Reply via email to