2017-08-25 525 views
1

我有一個乾淨的tibble,如下所示:R: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,必須命名。 我找不到一個簡單而簡單的方法。

謝謝你的幫助。

+0

我不知道我是否理解。如果Rt_count&Cus_count保留列,是否轉置數據框?或者你只是想將第一列轉換爲行名?對於後者,請查看'tibble :: column_to_rownames' –

+0

@ Z.Lin column_to_rownames(tt,var =「toto」) 錯誤:未找到列'num2' – gabx

+0

您必須指定將哪一列轉換爲rowname。嘗試'df%>%column_to_rownames(「created_week」)%>%as.data.frame()'? –

回答

1

轉貼的答案我的意見......

爲了創建DF $ created_week rownames而留下Rt_count & Cus_count欄目,你可以從tibble包使用column_to_rownames功能。

你會得到一個警告,在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 

編輯替代那並不是」 t取決於tibble的功能:

df <- as.data.frame(df) 
rownames(df) <- df$created_week 
df$created_week <- NULL 
+1

我只是想補充這個會折舊的。請參閱https://github.com/tidyverse/tibble/issues/123瞭解更多信息 – gabx

+0

Darn,我剛剛在一個月前瞭解了該功能。好吧,將包括一個替代品,只使用基礎包... –