【问题标题】:Combining two columns together and keep their original column name as a separate column将两列组合在一起并将其原始列名保留为单独的列
【发布时间】:2020-12-17 18:54:50
【问题描述】:

我正在尝试在 ggplot2 中用几行绘制一个图,并在该图中生成一个图例。目前我所有的数据都在不同的列中,需要我添加多个几何来获得多行。对于我的生活,我无法弄清楚如何为此生成一个图例。

我发现我的所有数据都需要在同一列中,它们的“类”在另一列中,以生成带有图例的多行。我现在似乎不知道应该如何组合这两列,同时保留它们的类数据。

假设我的数据结构是这样的:


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

我需要获取数据的方式是:

 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

如果这是可能的,我很想知道。据我所知,这应该可以让我在 ggplot 中获得图例。

提前非常感谢。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我们可以使用pivot_longer 转换为'long'格式

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

    -输出

    # 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
    

    【讨论】:

    • 啊,太棒了!非常感谢。这正是我想要的。我还有很多 tidyr/dplyr 函数需要学习。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 2020-07-11
    相关资源
    最近更新 更多