rdataframetidyversetibble

pivoting dataframe from one column across many in R?


I have this dataframe below:

my_df = tibble(name = c('car', 'mileage', 'year'), unk_1 = c('toyota', '1000', '2022'), unk_2 = c('hyundai', '50', '2024'))

The columns unk_1 and unk_2 are the way the data is read in R from csv format. these columns for this example are 2, in reality i have about 40. all start with same unk_#

I want to flip the data so that it looks like this:

 my_df = tibble('car' = c('toyota', 'hyundai'), 'mileage' = c('1000', '50'), year = c('2022', '2024')) 

I have tried pivot_longer but it has not worked as i do not want to make the columns unk_# but instead use the column called name


Solution

  • With data.table::transpose:

    data.table::transpose(my_df, make.names = "name")
    
    #       car mileage year
    # 1  toyota    1000 2022
    # 2 hyundai      50 2024
    

    In tidyr, you probably need to pivot long and wide:

    library(tidyr)
    my_df |> 
      pivot_longer(-name, names_to = "names") |> 
      pivot_wider() |> 
      select(-names)