Reputation: 1238
Having a dataframe like this:
data.frame(text = c("text2?????something more?????additional"), id = c("1?????2?????3"))
how is it possible to melt using the separation ????? and create new rows like this:
data.frame(text = c("text2", "something more", "additional"), id = c(1,2,3))
Upvotes: 0
Views: 46
Reputation: 887691
An option with unnest
and str_extract
library(dplyr)
library(tidyr)
library(stringr)
df1 %>%
summarise(across(everything(), str_extract_all, "[^?]+")) %>%
unnest(everything())
# A tibble: 3 x 2
# text id
# <chr> <chr>
#1 text2 1
#2 something more 2
#3 additional 3
Upvotes: 2
Reputation: 28705
df <-
data.frame(text = c("text2?????something more?????additional"), id = c("1?????2?????3"))
as.data.frame(lapply(df, function(x) strsplit(as.character(x), '\\?+')[[1]]))
# text id
# 1 text2 1
# 2 something more 2
# 3 additional 3
Upvotes: 2
Reputation: 146050
library(tidyr)
# fixing the data
d = data.frame(text = c("text2?????something more?????additional"), id = c("1?????2?????3"))
d %>% separate_rows(everything(), sep = "\\?+")
# text id
# 1 text2 1
# 2 something more 2
# 3 additional 3
Upvotes: 4