0

I need help writing a command to do the following:

I have two data frames (which I plan to combine into one to do some ggplotting) of the following form:

df1

|..D..|..A...|..B...|
| d1 | a11 | b11 |
| d2 | a12 | b12 |
| d3 | a13 | b13 |

df2

|..D.|..A....|..B....|
| d1 | a21 | b21 |
| d2 | a22 | b22 |
| d3 | a23 | b23 |

The values in the "D" column are the same for both tables, and the variables A and B have the same name, but the values are different. I need to get an output table of the following form:

df3

|..D..|..A...|..B...|Class|
| d1 | a11 | b11 | df1 |
| d2 | a12 | b12 | df1 |
| d3 | a13 | b13 | df1 |
| d1 | a21 | b21 | df2 |
| d2 | a22 | b22 | df2 |
| d3 | a23 | b23 | df2 |

I could just rbind both tables but I know (I think) that this can also be done with the "melt" function, but have not been able to make it happen.

pogibas
  • 27,303
  • 19
  • 84
  • 117
Mario Reyes
  • 385
  • 1
  • 2
  • 13

2 Answers2

1

reshape is more or less deprecated... If you want a tidyverse solution, you can do:

library(dplyr)
df3 <- row_binds(df1 = df1, df2 = df2, .id = "class")
meriops
  • 997
  • 7
  • 6
0

Just use cbind then rbind. Make use of R's recycling ability.

df1 <- cbind(mtcars,Class="df1")
df2 <- cbind(mtcars,Class="df2")

rbind(df1,df2)
Andre Elrico
  • 10,956
  • 6
  • 50
  • 69