Home > front end >  Is there an r function that can be used to split a fraction into two separate rows?
Is there an r function that can be used to split a fraction into two separate rows?

Time:03-15

I have a df that looks like the table below. I need to separate the Blood pressure vital sign rows into two separate vital sign rows. One that reads as "systolic blood pressure" (the higher number) and another that reads as "diastolic blood pressure" (the lower number).

Patient Vital sign Number time
1 oxygen 98 date/time
1 Heart rate 72 date/time
1 Blood pressure 120/80 date/time
2 Oxygen 92 date/time
2 Heart rate 103 date/time

I've tried to use the paste function to paste "systolic" in front of any character in the 'number column' that contains a "/". And then separate the rows that contain a "/" into two different rows, but I'm having a difficult time getting the syntax right.

Any suggestions?

CodePudding user response:

Use separate_rows from tidyr:

library(tidyverse)

dat %>%
   separate_rows(Number)

# A tibble: 6 x 4
  Patient Vital.sign     Number time     
    <int> <chr>          <chr>  <chr>    
1       1 oxygen         98     date/time
2       1 Heart rate     72     date/time
3       1 Blood pressure 120    date/time
4       1 Blood pressure 80     date/time
5       2 Oxygen         92     date/time
6       2 Heart rate     103    date/time

CodePudding user response:

We can use separate_rows on the 'Number' column

library(dplyr)
library(tidyr)
df1 %>%
    separate_rows(Number, convert = TRUE) %>%
     mutate(`Vital sign`= replace(`Vital sign`, 
    `Vital sign` == "Blood pressure", 
     c("systolic blood pressure", "diastolic blood pressure")))

-output

# A tibble: 6 × 4
  Patient `Vital sign`             Number time     
    <int> <chr>                     <int> <chr>    
1       1 oxygen                       98 date/time
2       1 Heart rate                   72 date/time
3       1 systolic blood pressure     120 date/time
4       1 diastolic blood pressure     80 date/time
5       2 Oxygen                       92 date/time
6       2 Heart rate                  103 date/time

data

df1 <- structure(list(Patient = c(1L, 1L, 1L, 2L, 2L), `Vital sign` = c("oxygen", 
"Heart rate", "Blood pressure", "Oxygen", "Heart rate"), Number = c("98", 
"72", "120/80", "92", "103"), time = c("date/time", "date/time", 
"date/time", "date/time", "date/time")), class = "data.frame", row.names = c(NA, 
-5L))
  •  Tags:  
  • r
  • Related