Home > front end >  Separate a column on arithmetic and comparative operators
Separate a column on arithmetic and comparative operators

Time:10-07

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

CodePudding user response:

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