mapvin vin
mapvin vin

Reputation: 81

Convert Vector to dataframe in R

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

Answers (3)

Tech Commodities
Tech Commodities

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

user438383
user438383

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

s_baldur
s_baldur

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

Related Questions