Mario Reyes
Mario Reyes

Reputation: 395

Need some advise to use reshape2:melt function for ggplot-ing

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.

Upvotes: 0

Views: 125

Answers (2)

meriops
meriops

Reputation: 1037

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")

Upvotes: 1

Andre Elrico
Andre Elrico

Reputation: 11480

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)

Upvotes: 0

Related Questions