Reputation: 81
I have a vector where there is a need to convert to dataframe. Is there a way to achieve this?
asd <- c("ABC\tCat + Catt1")
Expected output
df
ColA ColB
ABC Cat
ABC Catt1
Upvotes: 0
Views: 69
Reputation: 1959
library(tidyverse)
asd <- c("ABC\tCat + Catt1")
asd %>%
str_replace_all(regex("\\W+"), " ") %>%
as_tibble() %>%
separate(value, into = c("ColA", "A", "B"), sep = " ") %>%
pivot_longer(-ColA, values_to = "ColB") %>%
select(-name)
# A tibble: 2 × 2
ColA ColB
<chr> <chr>
1 ABC Cat
2 ABC Catt1
Upvotes: 0
Reputation: 6206
This is how you say... inelegant. But it works:
library(tidyverse)
df = as.data.frame(str_split(unlist(str_split(asd, "\t")), "\\+ ")) %>%
setnames(c("ColA", "ColB"))
ColA ColB
1 ABC Cat
2 ABC Catt1
Upvotes: 1
Reputation: 33498
Where there is a will, there is a way
strsplit(asd, "\t") |>
lapply(strsplit, " \\+ ") |>
as.data.frame() |>
setNames(c('ColA', 'ColB'))
ColA ColB
1 ABC Cat
2 ABC Catt1
Upvotes: 4