【问题标题】:pivot_longer the ouput of summarize_each with mean and sd functionspivot_longer summarise_each 的输出,带有 mean 和 sd 函数
【发布时间】:2019-11-13 17:19:34
【问题描述】:

我试图总结我的数据集中的所有列(它有很多列,尽管下面的代表示例只有 2 个),得到每个变量的均值和 sd。我希望输出为长格式。

#Example dataset
d <- iris %>% select(Sepal.Length,Sepal.Width)
names(d) <- c("SepalLength","SepalWidth")

#Summarizing and trying to make it long
s <- d %>% summarize_each( list(mean=mean,sd=sd) )  # has summar stats, but they are in wide format

# trying to pivot.
s %>% pivot_longer( ??? what do I put here ???)

我尝试了一些变体(例如:pivot_longer(names_to = "key", values_to = "value")),但总是收到错误消息。

【问题讨论】:

    标签: r dplyr pivot reshape2


    【解决方案1】:

    我们可以在里面使用select_helpers

    library(dplyr)
    library(tidyr)
    s %>%
       pivot_longer(everything())
    # A tibble: 4 x 2
    #  name             value
    #  <chr>            <dbl>
    #1 SepalLength_mean 5.84 
    #2 SepalWidth_mean  3.06 
    #3 SepalLength_sd   0.828
    #4 SepalWidth_sd    0.436
    

    或者如果我们需要 'SepalLength'、'SepalWidth' 作为两列

    s %>% 
       pivot_longer(cols = everything(), 
           names_to = c(".value", "statistic"), names_sep="_")
    # A tibble: 2 x 3
    #  statistic SepalLength SepalWidth
    #  <chr>           <dbl>      <dbl>
    #1 mean            5.84       3.06 
    #2 sd              0.828      0.436
    

    或者如果我们需要'mean','sd'作为两列

    s %>%
        pivot_longer(cols = everything(), 
           names_to = c("colNames", ".value"), names_sep="_")
    # A tibble: 2 x 3
    #  colNames     mean    sd
    #  <chr>       <dbl> <dbl>
    #1 SepalLength  5.84 0.828
    #2 SepalWidth   3.06 0.436
    

    或使用gather

    s %>%
      gather
    

    【讨论】:

      猜你喜欢
      • 2021-08-30
      • 2022-09-26
      • 2015-03-03
      • 2015-01-16
      • 2014-09-12
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多