Tengku Hanis
Tengku Hanis

Reputation: 87

Collapse several columns of data frame into one data frame

For some reason, I have a data in which a few columns are a set of data frame consist of one column. So, I want to "collapse" these columns of data frame into one data frame.

library(tidyverse)
df <- tibble(col1=1:5, 
              col2=tibble(newcol=LETTERS[1:5]),
              col3=tibble(newcol2=LETTERS[6:10]))
df
# A tibble: 5 x 3
   col1 col2$newcol col3$newcol2
  <int> <chr>       <chr>       
1     1 A           F           
2     2 B           G           
3     3 C           H           
4     4 D           I           
5     5 E           J  

I have tried unnest(), but, the function actually replicate data frame/tibble of col2 and col3 for each row of col1, which is not what I want.

df2 <- df %>% unnest(cols = c(col2, col3))
df2
# A tibble: 25 x 3
    col1 col2  col3 
   <int> <chr> <chr>
 1     1 A     F    
 2     1 B     G    
 3     1 C     H    
 4     1 D     I    
 5     1 E     J    
 6     2 A     F    
 7     2 B     G    
 8     2 C     H    
 9     2 D     I    
10     2 E     J    
# ... with 15 more rows

The result that I want is as below:

df3 <- tibble(col1=1:5, 
             newcol=LETTERS[1:5],
             newcol2=LETTERS[6:10])
df3
# A tibble: 5 x 3
   col1 newcol newcol2
  <int> <chr>  <chr>  
1     1 A      F      
2     2 B      G      
3     3 C      H      
4     4 D      I      
5     5 E      J  

Any idea how to do this? Any help is much appreciated.

Upvotes: 0

Views: 303

Answers (2)

Dome
Dome

Reputation: 60

it looks like you only want to change the column names or am I missing something here?

df<-df%>%mutate(col2=df$col2$newcol, col3=df$col3$newcol2)

After your comment, here you can find a more general version (might not be suitable for all use cases)

df1<-df%>%unnest(cols = c(1:3))%>%
group_by(col1)%>%
mutate(row=row_number())%>%
filter(row==col1)%>%
select(-row)

Upvotes: 1

TarJae
TarJae

Reputation: 78917

If I understand correct you have three dataframes each of them containing one column. Now you want to bring them all in one dataframe together. Then cbind is an option.

df3 <- cbind(df, col2, col3)

Output:

  col1 newcol newcol2
1    1      A       F
2    2      B       G
3    3      C       H
4    4      D       I
5    5      E       J

Upvotes: 0

Related Questions