How to melt and cast dataframes using dplyr?

后端 未结 3 1005
感情败类
感情败类 2021-01-30 13:03

Recently I am doing all my data manipulations using dplyr and it is an excellent tool for that. However I am unable to melt or cast a data frame using dplyr. Is there any way to

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-30 13:41

    To add to answers above using @Lovetoken's mini_iris example (this is too complex for a comment) - for those newcomers who do not understand what is meant by melt and casting.

    library(reshape2)
    library(tidyr)
    library(dplyr)
    
    # example data : `mini_iris`
    mini_iris <- iris[c(1, 51, 101), ]
    
    # mini_iris
    #Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
    #1            5.1         3.5          1.4         0.2     setosa
    #51           7.0         3.2          4.7         1.4 versicolor
    #101          6.3         3.3          6.0         2.5  virginica
    

    Melt is taking the dataframe and expanding into a long list of values. Not efficient but can be useful if you need to combine sets of data. Think of the structure of an icecube melting on a tabletop and spreading out.

    melted1 <- testiris %>% melt(id.vars = "Species")
    
    > nrow(melted1)
    [1] 12
    
    head(melted1)
    # Species     variable      value
    # 1     setosa Sepal.Length   5.1
    # 2 versicolor Sepal.Length   7.0
    # 3  virginica Sepal.Length   6.3
    # 4     setosa  Sepal.Width   3.5
    # 5 versicolor  Sepal.Width   3.2
    # 6  virginica  Sepal.Width   3.3
    

    You can see how the data has now been broken into many rows of value. The column names are now text within a variable column.

    casting will reassemble back to a data.table or data.frame.

提交回复
热议问题