Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bind two dataframes that have different columns names [duplicate]

I have two data-frames

The first data

        col1  col2 col3
A1       4     11  15
A2       2      9  17
A3       3      4   4 
B1       10     5   4   
B2        6     1   8
C1       12     1  12
C2        2     5   8
D1        4     1   6 
D2        2     1   8

The second data

          meancol1   meancol2 meancol3
meanA        3          8      12
meanB        8          3       6
meanC        7          3      10
meanD        3          1       7

I want to combine the two data-frames and keep the colnames of the first dataset so the result i want is :

          col1  col2 col3
    A1       4     11  15
    A2       2      9  17
    A3       3      4   4 
    B1       10     5   4   
    B2        6     1   8
    C1       12     1  12
    C2        2     5   8
    D1        4     1   6 
    D2        2     1   8
 meanA        3     8   12
 meanB        8     3    6
 meanC        7     3   10
 meanD        3     1    7

I tried : the following function

data_all <- rbind(df1,df2)

but it didn't work

I also tried the function bind_rows from dplyr package but this one create new columns.

Thank you

like image 464
Reda Avatar asked Jun 08 '26 14:06

Reda


2 Answers

You could always do:

colnames(df2) <- colnames(df1)

data_all <- rbind(df1, df2)

data_all
like image 195
Aron Strandberg Avatar answered Jun 11 '26 04:06

Aron Strandberg


A possible solution:

library(tidyverse)

df1 <- read.table(text = "        col1  col2 col3
A1       4     11  15
A2       2      9  17
A3       3      4   4 
B1       10     5   4   
B2        6     1   8
C1       12     1  12
C2        2     5   8
D1        4     1   6 
D2        2     1   8
", header=T)

df2 <- read.table(text = "meancol1   meancol2 meancol3
meanA        3          8      12
meanB        8          3       6
meanC        7          3      10
meanD        3          1       7
", header=T)

df2 %>% rename_with(~ str_remove(.x, "mean")) %>% 
  bind_rows(df1, .)

#>       col1 col2 col3
#> A1       4   11   15
#> A2       2    9   17
#> A3       3    4    4
#> B1      10    5    4
#> B2       6    1    8
#> C1      12    1   12
#> C2       2    5    8
#> D1       4    1    6
#> D2       2    1    8
#> meanA    3    8   12
#> meanB    8    3    6
#> meanC    7    3   10
#> meanD    3    1    7
like image 27
PaulS Avatar answered Jun 11 '26 03:06

PaulS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!