Separate a collapse column into multiple rows. Error when using separate_rows due to different number of elements

Hello,
This is my very first question here.
I want to separate the collapsed column into multiple rows. The data:

  x = 1:3,
  y = c("a", "d,e,f", "g,h"),
  z = c("A", "D,E", "G"), stringsAsFactors = FALSE
)```

Then I use: 
```  separate_rows(df,y,z)  ```

And I got the following error:

> separate_rows(df,y,z)
Error: All nested columns must have the same number of elements.
Call `rlang::last_error()` to see a backtrace

I understand why the error, since there are not the same number of elements in the nested columns.
The desired output would be

``` df2 <- data.frame(
  x = c(1, rep(2,3), rep(3,2)),
  y = c("a","d","e","f","g","h"),
  z = c("A","D","E",NA,"G",NA), stringsAsFactors = FALSE
) 
print(df2) ```

> df2
  x y    z
1 1 a    A
2 2 d    D
3 2 e    E
4 2 f <NA>
5 3 g    G
6 3 h <NA>

I'm using the tidyr version 0.8.3 and I cannot upgrade it (policy of the company I work).
Can you help me,
Thanks in advance.

I don't think you're looking for separate_rows() in this case, as it seems like you don't want to keep the association between the observations in x, y, z, as they are in your initial data frame, which is how separate_rows() works.

suppressPackageStartupMessages(library(tidyverse))
df1 <- data.frame(x = 1:3,
                  y = c("a", "d,e,f", "g,h"),
                  z = c("A", "D,E", "G"), stringsAsFactors = FALSE)

df1
#>   x     y   z
#> 1 1     a   A
#> 2 2 d,e,f D,E
#> 3 3   g,h   G

df2 <- separate_rows(df1, y)

df2
#>   x y   z
#> 1 1 a   A
#> 2 2 d D,E
#> 3 2 e D,E
#> 4 2 f D,E
#> 5 3 g   G
#> 6 3 h   G

df3 <- separate_rows(df2, z)

df3
#>   x y z
#> 1 1 a A
#> 2 2 d D
#> 3 2 d E
#> 4 2 e D
#> 5 2 e E
#> 6 2 f D
#> 7 2 f E
#> 8 3 g G
#> 9 3 h G

Created on 2019-12-19 by the reprex package (v0.3.0.9001)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.