Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Separate a column on arithmetic and comparative operators

Im trying to separate a column on arithmetic and comparative operators. The goal is to take the column and separate it into the left hand side and right hand side of the operator into two new columns and preserve the old. The pre is the current output, the post is the desired output, and below the code I would hopefully use. The "????" should I think be a regex expression that Im just not familiar with.

library(dplyr)
library(tidyr)

pre = data.frame(labels = c("<0", "0-2", "3-3", "4-5", "6+"))

post = data.frame(labels = c("<0", "0-2", "3-3", "4-5", "6+"),
                  LHS    = c(NA_character_, "0", "3", "4", "6"),
                  RHS    = c("0", "2", "3", "5", NA_character_))

pre%>%
  separate(col = labels,
           into = c("LHS", "RHS"),
           sep = ????,
           remove = FALSE) -> post

Thanks in advance

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

We could pass multiple characters within [] to match any of them

library(dplyr)
library(tidyr)
pre %>% 
  separate(labels, into = c("LHS", "RHS"), sep = "[-<+]",
    remove = FALSE, convert = TRUE)

-output

  labels LHS RHS
1     <0  NA   0
2    0-2   0   2
3    3-3   3   3
4    4-5   4   5
5     6+   6  NA
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading