Home > Enterprise >  Convert Vector to dataframe in R
Convert Vector to dataframe in R

Time:09-17

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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
  •  Tags:  
  • r
  • Related