Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten DataFrame into a single row with R

Tags:

r

Using R I want to reorganize the following mutli-row DataFrame,

       1          2       3
A  Apple     Orange   Grape
B    Car      Truck   Plane
C  House  Apartment  Garage

into this, single-row DataFrame.

     1_A     2_A    3_A  1_B    2_B    3_B    1_C        2_C     3_C
0  Apple  Orange  Grape  Car  Truck  Plane  House  Apartment  Garage

Thank you for your help!

like image 485
coal_canary Avatar asked Jan 21 '26 22:01

coal_canary


2 Answers

reshape solution, which will take care of all the naming and renaming in one step:

reshape(cbind(dat, id=1, time=rownames(dat)),
        direction="wide", sep="_", new.row.names=0)[-1]
#    1_A    2_A   3_A 1_B   2_B   3_B   1_C       2_C    3_C
#0 Apple Orange Grape Car Truck Plane House Apartment Garage
like image 65
thelatemail Avatar answered Jan 23 '26 12:01

thelatemail


Another solution with in tidyverse:

library(tidyverse)

df %>%
  rownames_to_column(var = "id") %>%
  pivot_wider(names_from = id, values_from = !id)

# A tibble: 1 x 9
  `1_A` `1_B` `1_C` `2_A`  `2_B` `2_C`     `3_A` `3_B` `3_C` 
  <chr> <chr> <chr> <chr>  <chr> <chr>     <chr> <chr> <chr> 
1 Apple Car   House Orange Truck Apartment Grape Plane Garage
like image 42
Anoushiravan R Avatar answered Jan 23 '26 11:01

Anoushiravan R