R:tibble 将列移动到行并命名列
R: tibble move columns to row & name columns
我有一个干净的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))
我正在考虑做与 base 中的 t() 相同的事情,结果是小标题,df$created_week 中的行及其名称,列是 Rt_count 和 Cus_count并且必须命名。
我找不到简单易行的方法。
感谢您的帮助。
重新发布我的评论作为答案...
为了从 df$created_week 创建行名,同时将 Rt_count & Cus_count 保留为列,您可以使用 [=13= 中的 column_to_rownames
函数] 包裹。
您会收到一条警告,指出不建议在小标题上设置行名称,但这没关系,因为我们会将其转换回 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
我有一个干净的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))
我正在考虑做与 base 中的 t() 相同的事情,结果是小标题,df$created_week 中的行及其名称,列是 Rt_count 和 Cus_count并且必须命名。 我找不到简单易行的方法。
感谢您的帮助。
重新发布我的评论作为答案...
为了从 df$created_week 创建行名,同时将 Rt_count & Cus_count 保留为列,您可以使用 [=13= 中的 column_to_rownames
函数] 包裹。
您会收到一条警告,指出不建议在小标题上设置行名称,但这没关系,因为我们会将其转换回 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