Home > database >  Converting a matrix within a dataframe to character columns/vectors in R
Converting a matrix within a dataframe to character columns/vectors in R

Time:08-04

The code adds on a matrix to the dataframe showing words enclosed in asterisks from col1. How can I convert this matrix col2[,1] and col2[,2] into columns so it is just one dataframe?

library(stringr)
library(dplyr)

col1<-c("**sometimes** i code in python",
        "I like **walks** in the park",
        "I **often** do **exercise**")

df<- data.frame(col1, stringsAsFactors = FALSE)%>%
  mutate(col2 = str_extract_all(col1, "\\*\\*[^* ] \\*\\*",simplify=TRUE))

CodePudding user response:

Turn the column into a data frame, then unnest()

library(stringr)
library(dplyr)
library(tidyr)

df %>%
  mutate_at("col2", as.data.frame) |> 
  unnest(col2)
#> # A tibble: 3 × 3
#>   col1                           V1            V2            
#>   <chr>                          <chr>         <chr>         
#> 1 **sometimes** i code in python **sometimes** ""            
#> 2 I like **walks** in the park   **walks**     ""            
#> 3 I **often** do **exercise**    **often**     "**exercise**"

Created on 2022-08-03 by the reprex package (v2.0.1)

  •  Tags:  
  • r
  • Related