Below is an example to convert tibble to a longer format.
I am getting the following error.
Error: In row 3, can't recycle input of size 5 to size 0.
Run `rlang::last_error()` to see where the error occurred.
How do I fix the error?
It should involve unnesting selected columns which are lists
unnest(where(is.list))
A possible solution should also include converting all numeric(0) and NaN to NA.
library(tidyverse)
tbl <- tibble(
a_X_values = list(numeric(0), c(3, NaN), c(4, 5, 6, NaN, NaN)),
a_Y_values = list(5, NaN, numeric(0)),
b_X_values = c(7, 8, 9),
b_Y_values = c(NA, NaN, 1)
)
tbl_longer <- tbl %>%
unnest(where(is.list)) %>%
pivot_longer(cols = everything(),
names_to = c("alpha", "beta", ".value"), names_sep = "_")
CodePudding user response:
Problem seems to be with the empty numeric values that are contained in lists, if they weren't listed your data.frame wouldn't work
If we apply a function over the list, searching for empty numeric values, replacing them with NA we can then use your code to pivot longer
tbl %>%
rowwise() %>%
mutate(across(where(is.list), \(x) ifelse(length(x) == 0, list(NA), list(x)))) %>%
unnest(where(is.list)) %>%
pivot_longer(cols = everything(),
names_to = c("alpha", "beta", ".value"), names_sep = "_") %>%
ungroup()
alpha beta values
<chr> <chr> <dbl>
1 a X NA
2 a Y 5
3 b X 7
4 b Y NA
5 a X 3
6 a Y NaN
7 b X 8
8 b Y NaN
9 a X NaN
10 a Y NaN