[R] concatenating columns in data.frame
Micha Silver
t@v|b@r @end|ng |rom gm@||@com
Thu Jul 1 16:36:06 CEST 2021
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
More information about the R-help
mailing list