Reputation: 1807
I have a dataframe with two sets of columns v
and t
amongst others.
library(tidyverse)
(df <-
tibble(id = 1,
v1 = 1, v2 = 2, v3 = 3,
t1 = "a", t2 = "b", t3 = "c"
)
)
#> # A tibble: 1 × 7
#> id v1 v2 v3 t1 t2 t3
#> <dbl> <dbl> <dbl> <dbl> <chr> <chr> <chr>
#> 1 1 1 2 3 a b c
I want my output to be three rows long. I think one way I can do this is by nesting the similar columns, and unnest_longer
. But this is not allowed.
## unnest_longer can't handle multiple cols
df %>%
nest(v = c(v1, v2, v3),
t = c(t1, t2, t3)) %>%
unnest_longer(c("v", "t"))
#> Error: Must extract column with a single valid subscript.
#> x Subscript `var` has size 2 but must be size 1.
Is it possible to unnest_longer
multiple columns at once?
Upvotes: 0
Views: 291
Reputation: 887223
According to the documentation of ?unnest_longer
takes only a single col
umn
.col, col - List-column to extract components from.
whereas the argument in unnest
is cols
(which can unnest more than one column)
Perhaps, the OP wanted to use pivot_longer
instead of nest/unnest
i.e. reshape to 'long' format by specifying the cols
without the 'id' column, return the .value
and capture the non digits (\\D+
) in the column name as names_pattern
library(dplyr)
library(tidyr)
df %>%
pivot_longer(cols = -id, names_to = ".value",
names_pattern = "^(\\D+).*")
# A tibble: 3 × 3
# id v t
# <dbl> <dbl> <chr>
#1 1 1 a
#2 1 2 b
#3 1 3 c
Upvotes: 1