在 R 中旋转 table

Rotate table in R

我怎样才能 melt/reshape/rotate 我的 table 从此:

          profit     lost      obs    fc.mape
mean    3724.743 804.1835 427.8899 0.21037696
std.dev  677.171 406.1391 372.5544 0.06072549

为此:

         mean   std.dev
profit   x
lost     x
obs      x
fc.mape  x

这是一个tidyverse解决方案。我觉得它太复杂了,但它确实有效。也许还有更简单的。

library(dplyr)
library(tidyr)

df1 %>%
  mutate(id = row.names(.)) %>%
  pivot_longer(
    cols = -id, 
    names_to = "stat"
  ) %>%
  group_by(id) %>%
  mutate(n = row_number()) %>%
  ungroup() %>%
  pivot_wider(
    id_cols = c(n, stat),
    names_from = id,
    values_from = value
  ) %>%
  select(-n)
## A tibble: 4 x 3
#  stat        mean  std.dev
#  <chr>      <dbl>    <dbl>
#1 profit  3725.    677.    
#2 lost     804.    406.    
#3 obs      428.    373.    
#4 fc.mape    0.210   0.0607

数据

df1 <-
structure(list(profit = c(3724.743, 677.171), lost = c(804.1835, 
406.1391), obs = c(427.8899, 372.5544), fc.mape = c(0.21037696, 
0.06072549)), class = "data.frame", row.names = c("mean", "std.dev"))