Use R to combine duplicate columns -


i have table 4 columns columns 1,3 , columns 2,4 representing same variable.

codes    description        codes     description xxxxx    describes xxxxx    zzzzz     describes zzzzz yyyyy    describes yyyyy    12345     describes 12345 

i want convert table

codes    description        xxxxx    describes xxxxx     zzzzz    describes zzzzz yyyyy    describes yyyyy   12345    describes 12345 

right doing use :

df_temp <- df[,3:4] df <- df[, - c(3, 4)] df <- rbind(df, df_temp) 

but have several table , method doesn't seem efficient. possible using %>% or writing function?

you can use duplicated function dynamically identify , rbind duplicate columns:

combine_duplicates <- function(df) {    duplicate_columns <- duplicates(colnames(df))    return(rbind(df[,duplicate_columns], df[,!duplicate_columns])) } combine_duplicates(df) 

this work on table, provided duplicate columns in same order original column names (e.g. c("codes", "description", "codes", "description") work, c("codes", "description", "description", "codes") not) , there no columns without duplicates in table.


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -