Author

Zoë Turner

Published

March 12, 2024

Modified

March 12, 2024

Create data

This was written originally in an Excel spreadsheet and used {datapasta} to copy into R as code to build the same data frame. {datapasta} can be access through RStudio as an Addin as well as code. Find out more about {datapasta} from the Introduction to R and R Studio course.

data <- tibble::tribble(
    ~Patient,          ~Codes,
  "PatientA", "A01, A02, A03",
  "PatientB", "B01; B02; B03",
  "PatientC", "C01; C03",
  "PatientD", "D01. D02. D03"
  )

Separate codes by position

Separate into columns in the order data appears

library(tidyverse)

data |> 
  tidyr::separate(Codes, c("col1", "col2", "col3"))
# A tibble: 4 × 4
  Patient  col1  col2  col3 
  <chr>    <chr> <chr> <chr>
1 PatientA A01   A02   A03  
2 PatientB B01   B02   B03  
3 PatientC C01   C03   <NA> 
4 PatientD D01   D02   D03  

https://tidyr.tidyverse.org/reference/separate.html

Add a pivot

To move wide data to longer:

data |> 
  tidyr::separate(Codes, c("col1", "col2", "col3")) |> 
  tidyr::pivot_longer(cols = c(starts_with("col")),
               names_to = "type")
# A tibble: 12 × 3
   Patient  type  value
   <chr>    <chr> <chr>
 1 PatientA col1  A01  
 2 PatientA col2  A02  
 3 PatientA col3  A03  
 4 PatientB col1  B01  
 5 PatientB col2  B02  
 6 PatientB col3  B03  
 7 PatientC col1  C01  
 8 PatientC col2  C03  
 9 PatientC col3  <NA> 
10 PatientD col1  D01  
11 PatientD col2  D02  
12 PatientD col3  D03  
Back to top

Reuse

CC0

Citation

For attribution, please cite this work as:
Turner, Zoë. 2024. “Showcasing a Function - `Separate()`.” March 12, 2024. https://nhsrcommunity.com/blog/showcasing-functions-separate.html.