Search code examples
rstringlistcut

R - return to numbers from cut


I have a table with the cuts in intervals like:

    bin targets casos   prop phyp      logit
(-2,-1]     193  6144 0.0314    0 -3.4286244
  (-1,3]     128   431 0.2970    1 -0.8617025
 (3,11]     137   245 0.5592    1  0.2378497

I want to get the original cuts. I tried with:

a<-strsplit(as.character(pl$table[,'bin']), ' ')

And then I tried to split each row with:

lapply(a, function(x) strsplit(x, ",")[1] )

But I don't get the expected result, which is:

(-1,3,11)

Is there a better way to achieve this? What else do I need to do to get to the result?

Thanks.


Solution

  • In your example, there are more bounds than you say you are hoping to retrieve. This will give you all bounds:

    d <- read.table(text='    bin targets casos   prop phyp      logit
    "(-2,-1]"     193  6144 0.0314    0 -3.4286244
      "(1,3]"     128   431 0.2970    1 -0.8617025
     "(3,11]"     137   245 0.5592    1  0.2378497', header=T)
    
    strings <- as.character(levels(d$bin))
    strings <- substr(strings, 2, nchar(strings)-1)
    unique(unlist(strsplit(strings, ",")))
    # [1] "-2" "-1" "1"  "3"  "11"
    

    If you only wanted the upper bounds, this will work:

    strings <- as.character(levels(d$bin))
    strings <- sapply(strsplit(strings, ","), function(l){ l[2] })
    strings <- substr(strings, 1, nchar(strings)-1)
    unique(strings)
    # [1] "-1" "3"  "11"