简体   繁体   中英

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

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

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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM