Home > Enterprise >  merge values of different type using pivot_longer
merge values of different type using pivot_longer

Time:07-29

Below is an example, I want to use create a tibble in longer format with 3 columns

  1. Column 1; name - alpha; contains a and b
  2. Column 2; name - beta; contains X and Y
  3. Column 3; name - values; contains values

I am getting an error

Error in UseMethod("pivot_longer") : 
  no applicable method for 'pivot_longer' applied to an object of class "character"

Is there way to create a longer tibble

  1. I believe all values that will go to values column, should be converted to numeric
  2. If a cell have multiple values, we may need to create an extra column values2 to hold it.

library(tidyverse)

# create empty list
b_X_values <- list()
b_Y_values <- list()

# fill list
for (iter in 1:2)
{
  b_X_values[[iter]] <- runif(1)
  b_Y_values[[iter]] <- runif(iter)
}

# tibble
tbl <- tibble(a_X_values = runif(2),
              a_Y_values = runif(2),
              b_X_values = b_X_values,
              b_Y_values = b_Y_values)

# pivot tibble
tbl <- pivot_longer(cols = c("a_X_values", "a_Y_values",
                             "b_X_values", "b_Y_values"),
                    names_to = c("alpha", "beta", ".values"),
                    names_sep = "_")

CodePudding user response:

We may need to unnest the list columns first

library(dplyr)
library(tidyr)
tbl %>% 
  unnest(where(is.list)) %>% 
  pivot_longer(cols = everything(), 
     names_to = c("alpha", "beta", ".value"), names_sep = "_") %>%
  distinct

-output

# A tibble: 9 × 3
  alpha beta  values
  <chr> <chr>  <dbl>
1 a     X      0.114
2 a     Y      0.698
3 b     X      0.662
4 b     Y      0.552
5 a     X      0.729
6 a     Y      0.880
7 b     X      0.980
8 b     Y      0.300
9 b     Y      0.912
  • Related