0

I have this data frame:

data_df <- data.frame(requests = c(300,400,500), approvals = c(35,48,52), loans = c(14, 22, 23), id_month = c("Jan-19","Feb-19","Mar-19"), stringsAsFactors = FALSE) 

I want to set the table using months as cols. So firstly I transposed it:

data_df %>% t() 

This is the result:

 [,1] [,2] [,3] requests "300" "400" "500" approvals "35" "48" "52" loans "14" "22" "23" id_month "Jan-19" "Feb-19" "Mar-19" 

But I don't know how to put row "id_month" as column header. Besides all values seem to be characters and not numbers (perhaps because each column contains a character row). This should be the expected result:

 Jan-19 Feb-19 Mar-19 requests 300 400 500 approvals 35 48 52 loans 14 22 23 

Any help in tidy verse will be greatly appreciated. Thank you in advance.

2 Answers 2

2
library(dplyr) df <- data_df %>% select(-4) %>% t() %>% as.data.frame() names(df)<-data_df$id_month df Jan-19 Feb-19 Mar-19 requests 300 400 500 approvals 35 48 52 loans 14 22 23 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @Duck, works fine for a Tidyverse solution.
2

We could use transpose from data.table

out <- data.table::transpose(data_df, make.names = 'id_month') row.names(out) <- names(data_df)[-4] out # Jan-19 Feb-19 Mar-19 #requests 300 400 500 #approvals 35 48 52 #loans 14 22 23 

If we don't need row names and would be okay with a column

data.table::transpose(data_df, make.names = 'id_month', keep.names = 'rn') # rn Jan-19 Feb-19 Mar-19 #1 requests 300 400 500 #2 approvals 35 48 52 #3 loans 14 22 23 

Or using base R

`colnames<-`(t(data_df[-4]), data_df$id_month) # Jan-19 Feb-19 Mar-19 #requests 300 400 500 #approvals 35 48 52 #loans 14 22 23 

1 Comment

Thank you very much @akrun, I will read more about data.table, it seems quite straightforward to use it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.