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.