2

I'm trying to reproduce the pandas (Python) explode method using R.

This is the data I have:

d = {"SN":[1,2],"Age":[21,15],"Name":["John;Luis","Dora"]}
df = pd.DataFrame(d)
df

From there I use split the names separated by ";" and use the explode method

df["Name"] = df["Name"].apply(lambda x: x.split(";"))
df.explode("Name")

The result I get is:

enter image description here

Now I'm trying to do the same using R. I have this part of the code, that accounts for the first step

df <- data.frame("SN" = 1:2, "Age" = c(21,15), "Name" = c("John;Luis","Dora"))
df$Name <- as.character(df$Name)
df = df %>% 
    mutate(Name =  strsplit(Name,split=';', fixed=TRUE) )

But I'm not finding the equivalent to .explode()

camille
  • 16,432
  • 18
  • 38
  • 60
Luis Ramon Ramirez Rodriguez
  • 9,591
  • 27
  • 102
  • 181

1 Answers1

3

We can use separate_rows in R instead of strsplit and then expand the rows

library(tidyr)
library(dplyr)   
df %>%
     separate_rows(Name)
#  SN Age Name
#1  1  21 John
#2  1  21 Luis
#3  2  15 Dora

With the OP method, the strsplit returns a list of vector, which can be unnested

df %>% 
   mutate(Name =  strsplit(Name,split=';', fixed=TRUE) ) %>%
   unnest(c(Name))
akrun
  • 874,273
  • 37
  • 540
  • 662