r - How to join without losing information? -


i have several data frames following structure:

   january        february       march       april     id    b      id    b      id   b    id     b    1    4  4       1   2  3       3  9  7    1    4   3    2    3  5       2   2  7       2  2  4    4    6   2    3    6  8       4   9  9                  2    3   5     4    7  8   

i bring them 1 single data frame contains ´na´ missing id' , there corresponding attributes. results has might like:

                id   jana janb   feba  febb    mara marb   apra aprb                 1     4     4     2     3       na   na     4    3                 2     3     5     2     7       2    4      3    5                 3     6     8     na    na      9    7      na   na                 4     7     8     9     9       na   na     6    2 

given data:

           id<-c(1,2,3,4)            a<-c(4,3,6,7)            b<-c(4,5,8,8)            jan<-data.frame(id,a,b)            id<-c(1,2,4)            a<-c(2,2,9)            b<-c(3,7,9)            feb<-data.frame(id,a,b)            id<-c(3,2)            a<-c(9,2)            b<-c(7,4)            mar<-data.frame(id,a,b)            id<-c(1,4,2)            a<-c(4,6,3)            b<-c(6,2,5)            apr<-data.frame(id,a,b) 

what have tried:

          test <- rbind(jan, feb,mar,apr)           test <- rbind.fill(jan, feb, mar,apr)  

you can use merge within reduce.

first, let's prepare list data , change column names jana, janb, feba, ...

list_df <- list(   jan = jan,   feb = feb,   mar = mar,   apr = apr ) list_df <- lapply(names(list_df), function(name_month){   df_month <- list_df[[name_month]]   names(df_month)[-1] <- paste0(name_month, names(df_month)[-1])   df_month }) 

reduce merge of them.

reduce(function(x, y) merge(x, y, = "id", = true), list_df) 

Comments