Home > Blockchain >  extracting list items in r data frame
extracting list items in r data frame

Time:01-15

I have a data frame with two columns: ID and product. The product contains a list of items like the ones below:

ID Product
1 'desk','chair','clock'
2 NA
3 'pen'

I want to extract every single product in a separate row with the corresponding ID, as below:

ID Product
1 'desk'
1 'chair'
1 'clock'
3 'pen'

It would be appreciated if you had any suggestions.

CodePudding user response:

You can do it with separate.

library(tidyverse)

df <- data.frame(
  id = c(1,2,3),
  product=c('desk, chair, clock', NA, 'pen')
) 

df |> 
  separate_rows(product) |> 
  drop_na()
#> # A tibble: 4 × 2
#>      id product
#>   <dbl> <chr>  
#> 1     1 desk   
#> 2     1 chair  
#> 3     1 clock  
#> 4     3 pen

CodePudding user response:

You can do it with tidyr lib separate_rows

library(tidyr)

df = df %>%
  separate_rows(Product, sep = ",")

CodePudding user response:

Beside the above answers, I tried this method and works fine as well.

result_df <-  unnest(df, Product)
  • Related