Search code examples
rtransformationmelt

Combine two dfs with different column names and then melt


I want to combine two data frames but melt them into different columns based on below:

treatment<-c('control','noise')
weight<-c(0.01872556,0.01575400)
sd<-c(0.008540041,0.007460524)

df1<-data.frame(treatment,weight,sd)

treatment2<-c('control','noise')
area<-c(0.79809444,0.68014667)
sd2<-c(0.337949414,0.294295847)

df2<-data.frame(treatment2,area,sd2)

And I wanted to combine them and create a data frame which should look like this:

treatment var sum sd
control area 0.79809444 0.337949414
noise area 0.68014667 0.294295847
control weight 0.01872556 0.008540041
noise weight 0.01575400 0.01575400

I tried this various ways, googled various ways and ended up exporting each data frame into a csv then combining them in excel, re-importing into R for analysis.

Is there a simpler solution?


Solution

  • You could use

    library(tidyr)
    library(dplyr)
    
    df2 %>% 
      rename(sd = sd2, treatment = treatment2) %>% 
      pivot_longer(area, names_to = "var", values_to = "sum") %>% 
      bind_rows(pivot_longer(df1, weight, names_to = "var", values_to = "sum")) %>% 
      select(treatment, var, sum, sd)
    

    to get

    # A tibble: 4 x 4
      treatment var       sum      sd
      <chr>     <chr>   <dbl>   <dbl>
    1 control   area   0.798  0.338  
    2 noise     area   0.680  0.294  
    3 control   weight 0.0187 0.00854
    4 noise     weight 0.0158 0.00746