Keipi
Keipi

Reputation: 142

Combining two columns together and keep their original column name as a separate column

I'm trying to make a plot in ggplot2 with several lines and produce a legend in that plot. Currently all my data is in separate columns, requiring me to add multiple geoms to get several lines. For the life of me, I can't figure out how to generate a legend for this.

I've found that all my data needs to be in the same column, with their 'class' in another column to produce several lines with a legend. I now can't seem to figure out how I should combine these two columns while retaining their class data.

Let's say I have my data structure like so:


iris$Numbers <- seq(1:150)
iris %<>% select(Numbers, Sepal.Width, Sepal.Length)

 Numbers Sepal.Width Sepal.Length
     <int>       <dbl>        <dbl>
 1       1         3.5          5.1
 2       2         3            4.9
 3       3         3.2          4.7

The way I'd need to get my data would be:

 Numbers       Data        Class
     <int>       <dbl>        <chr>
 1       1         3.5          Sepal.Width
 2       1         5.1          Sepal.Length
 3       2         3            Sepal.Width
 4       2         4.9          Sepal.Length
 5       3         3.2          Sepal.Width
 6       3         4.7          Sepal.Length

If this is possible, I'd love to know. To my knowledge, this should allow me to get the legend in the ggplot.

Huge thanks in advance.

Upvotes: 1

Views: 189

Answers (1)

akrun
akrun

Reputation: 887108

We can use pivot_longer to convert to 'long' format

library(dplyr)
library(tidyr)
iris %>%
   pivot_longer(cols = -Numbers, names_to = 'Class', values_to = 'Data')

-output

# A tibble: 300 x 3
#   Numbers Class         Data
#     <int> <chr>        <dbl>
# 1       1 Sepal.Width    3.5
# 2       1 Sepal.Length   5.1
# 3       2 Sepal.Width    3  
# 4       2 Sepal.Length   4.9
# 5       3 Sepal.Width    3.2
# 6       3 Sepal.Length   4.7
# 7       4 Sepal.Width    3.1
# 8       4 Sepal.Length   4.6
# 9       5 Sepal.Width    3.6
#10       5 Sepal.Length   5  
# … with 290 more rows

Upvotes: 1

Related Questions