How to switch these columns and rows in R data frame?

Viewed 74

Suppose we have this data frame:

avg_1 avg_2 avg_3 avg_4
132   123   23    214
DF    DM    RF    RM

How can I convert this in R so that the output is a new data frame that looks like:

avg key
132 DF
123 DM
23  RF
214 RM

I have tried using pivot_longer from tidyverse, but the trouble is that I'm also trying to rename the columns to avg and key. Can anyone help?

3 Answers

In base R I would try:

setNames(data.frame(t(df), row.names = NULL), c("avg", "key"))

Output

  avg key
1 132  DF
2 123  DM
3  23  RF
4 214  RM

Does this work:

library(dplyr)
library(purrr)
library(tibble)
t(df) %>% as.tibble() %>% set_names(c('avg','key')) %>% type.convert(as.is = T)
# A tibble: 4 x 2
    avg key  
  <int> <chr>
1   132 DF   
2   123 DM   
3    23 RF   
4   214 RM   

And here is a solution with R builtin methods:

x <- t(your.data.fram)
names(x) <- c("avg", "key")

Note that you might also want to change the data types to numeric and factor, if they are something different, e.g.

x$avg <- as.numeric(x$avg)
x$key <- as.factor(x$key)
Related