2

我有一个干净的 tibble,如下图所示:

df <- structure(list(created_week = c(31, 32, 33, 34), Rt_count = c(7, 
6, 5, 0), Cus_count = c(2, 1, 2, 1)), class = c("tbl_df", "tbl", 
"data.frame"), .Names = c("created_week", "Rt_count", "Cus_count"
), row.names = c(NA, -4L))

我正在寻找与基础的 t() 相同的操作,以 tibble 作为结果,并将 df$created_week 的行及其名称,列是 Rt_count 和 Cus_count 并且必须命名。我找不到简单易行的方法。

谢谢你的帮助。

4

1 回答 1

3

重新发布我的评论作为答案...

为了从 df$created_week 创建行名,同时将 Rt_count 和 Cus_count 作为列,您可以使用包中的column_to_rownames函数tibble

您会收到警告,不推荐在 tibble 上设置行名称,但这很好,因为我们会将其转换回 data.frame:

library(dplyr); library(tibble)

df %>% 
  column_to_rownames("created_week") %>% 
  as.data.frame()

   Rt_count Cus_count
31        7         2
32        6         1
33        5         2
34        0         1

编辑不依赖于tibble功能的替代方案:

df <- as.data.frame(df)
rownames(df) <- df$created_week
df$created_week <- NULL
于 2017-08-25T10:08:45.623 回答