gabx
gabx

Reputation: 482

R: tibble move columns to row & name columns

I have a clean tibble, as shown below:

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))

I am looking at doing same as t() from base, with a tibble as result and row from df$created_week with their name, columns are Rt_count and Cus_count and must be named. I can't find a simple and easy way.

Thank you for help.

Upvotes: 2

Views: 5334

Answers (1)

Z.Lin
Z.Lin

Reputation: 29095

Reposting my comment as answer...

In order to create rownames from df$created_week while leaving Rt_count & Cus_count as columns, you can use the column_to_rownames function from the tibble package.

You'll get a warning that setting row names on a tibble is deprecated, but that's fine since we'll convert it back to 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

Edit for alternative that doesn't depend on tibble's function:

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

Upvotes: 3

Related Questions