Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the breakpoints from cut [duplicate]

Tags:

r

The documentation of the cut function gives "one way to extract the breakpoints"

aaa <- c(1,2,3,4,5,2,3,4,5,6,7)
labs <- levels(cut(aaa, 3))
cbind(lower = as.numeric( sub("\\((.+),.*", "\\1", labs) ),
      upper = as.numeric( sub("[^,]*,([^]]*)\\]", "\\1", labs) ))

#      lower upper
# [1,] 0.994  3.00
# [2,] 3.000  5.00
# [3,] 5.000  7.01

Is there another - build-in - way to extract the breakpoints?

like image 287
Paul Rougieux Avatar asked Feb 08 '23 06:02

Paul Rougieux


1 Answers

1) read.table I don't think there is anything directly intended for this but this is shorter:

read.table(text = gsub("[^.0-9]", " ", labs), col.names = c("lower", "upper"))

giving this data.frame:

  lower upper
1 0.994  3.00
2 3.000  5.00
3 5.000  7.01

2) gsubfn::strapply and this is another possibility:

library(gsubfn)

strapply(labs, "[.0-9]+", as.numeric, simplify = rbind)

giving this matrix:

      [,1] [,2]
[1,] 0.994 3.00
[2,] 3.000 5.00
[3,] 5.000 7.01

3) gsubfn::read.pattern and another:

library(gsubfn)

read.pattern(text = labs, pattern = ".(.+),(.+).", col.names = c("lower", "upper"))

giving:

  lower upper
1 0.994  3.00
2 3.000  5.00
3 5.000  7.01
like image 184
G. Grothendieck Avatar answered Feb 16 '23 02:02

G. Grothendieck