Reshape dataframe with first column values as column names and second column values as row values in r

Viewed 202

I have a dataframe that looks like that, just with more values and variables:

Column_Name_1 Column_Name_2
Value 1 Value 3
Value 2 Value 4

And i want it to look like that:

Value 1 Value 2
Value 3 Value 4

Do you maybe have an easy solution for that? Thanks in advance

3 Answers

Try unstack + data.frame

> data.frame(t(unstack(rev(df))), row.names = NULL, check.names = FALSE)
  Value 1 Value 2
1 Value 3 Value 4

Data

> dput(df)
structure(list(Column_Name_1 = c("Value 1", "Value 2"), Column_Name_2 = c("Value 3", 
"Value 4")), class = "data.frame", row.names = c(NA, -2L))

Here's an option -

setNames(data.frame(t(df[-1]), row.names = NULL), df$Column_Name_1)

#  Value 1 Value 2
#1 Value 3 Value 4

A tidyverse solution:

df %>% 
  tibble::column_to_rownames("Column_Name_1") %>% 
  t() %>% as_tibble()

# A tibble: 1 x 2
  `Value 1` `Value 2`
  <chr>     <chr>    
1 Value 3   Value 4  
Related