user3141592
user3141592

Reputation: 121

How to extract the endpoints of an interval in R?

I've searched, but I cannot find an answer. I want to further process the data of a plot I've created in R with geom_bin2d. I've extracted the bins (intervals) from such a plot using

> library(ggplot2)
> my_plot <- ggplot(diamonds, aes(x = x, y = y))+ geom_bin2d(bins=3)
> plot_data <- ggplot_build(my_plot)
> data <- plot_data$data[[1]]
> data$xbin[[1]]
[1] [0,3.58]
Levels: [0,3.58] (3.58,7.16] (7.16,10.7] (10.7,14.3]

Nothing I tried worked, including min and mean. How do I access the endpoints of such an interval like data$xbin[[1]]?

(Update: I turned the example into a complete test case based on a built-in data set.)

Upvotes: 2

Views: 954

Answers (1)

Paulo E. Cardoso
Paulo E. Cardoso

Reputation: 5856

Something like

library(stringr)
x <- cut(seq(1:5), breaks = 2)
as.numeric(unlist(str_extract_all(as.character(x[1]), "\\d+\\.*\\d*")))

or in you example

my_plot <- ggplot(diamonds, aes(x = x, y = y))+ geom_bin2d(bins=3)
plot_data <- ggplot_build(my_plot)
data <- plot_data$data[[1]]
x <- data$xbin[[1]]
as.numeric(unlist(str_extract_all(as.character(x), "\\d+\\.*\\d*")))[2]
3.58

Upvotes: 3

Related Questions