How to melt and cast dataframes using dplyr?

后端 未结 3 1000
感情败类
感情败类 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:32

    In addition, cast can be using tidyr::spread()

    Example for you

    library(reshape2)
    library(tidyr)
    library(dplyr)
    
    # example data : `mini_iris`
    (mini_iris <- iris[c(1, 51, 101), ])
    
    # melt
    (melted1 <- mini_iris %>% melt(id.vars = "Species"))         # on reshape2
    (melted2 <- mini_iris %>% gather(variable, value, -Species)) # on tidyr
    
    # cast
    melted1 %>% dcast(Species ~ variable, value.var = "value") # on reshape2
    melted2 %>% spread(variable, value)                        # on tidyr
    

提交回复
热议问题