如何使用“段"计算区域内有多少数据点? [英] How to count how many data point inside a region using 'segments'?

查看:88
本文介绍了如何使用“段"计算区域内有多少数据点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有办法找出R上指定区域内有多少个数据点?例如,这是我的代码:

Is there a way to find out how many data points fall within a specified region on R? For example, this is my code:

data = read.csv("data.csv")
plot(data$X, data$Y, ylab = "Y", xlab = "X", pch = 1, col = unclass(data$classes), cex = 0.5, cex.axis = 0.5, main = "Y vs X Plot")
par(fig = c(0, 1, 0, 1), oma = c(0, 0, 0, 0), mar = c(0, 0, 0, 0), new = TRUE)
segments(-0.02, 0.36, 0.15, 0.36, col = c("purple"), lty = 1, lwd = 1)
segments(0.15, 0.35, 0.15, 0.9, col = c("purple"), lty = 1, lwd = 1)

哪个给我这个情节:

Y与X的图

我想知道有多少红色圆圈落在左侧矩形区域内(带有紫色边框的圆圈)或放置在其边界上.有没有办法在R上做到这一点?

I want to know how many red circles fall within the rectangular region on the left (the one with the purple borders) or got placed on its boundary. Is there a way to do this on R?

推荐答案

不一定使用segments()本身,但这是使用数字本身的一种方法.

Not necessarily using segments() itself, but here's a way of doing it with the numbers themselves.

我没有您的数据,所以这里有一些假数据:

I don't have your data, so here's some fake data:

x <- rnorm(100)
y <- rnorm(100)
class <- sample(1:2, 100, replace=T)
plot(x,y, col=class)

# region we're interested in
xmin <- 0
xmax <- 1
ymin <- 0
ymax <- 1
rect(xmin, ymin, xmax, ymax)  
# rect was easier for what I wanted to show, but you can use numbers the same way

盒子里有多少个点?

sum(x>xmin & x<xmax & y>ymin & y<ymax & class==2)
# [1] 11
# your results will vary

盒子的边框上有几个点?

How many points are on the border of the box?

sum(((x>xmin & x<xmax & y==ymin) | (x>xmin & x<xmax & y==ymax) | (y>ymin & y<ymax & x==xmin) | (y>ymin & y<ymax & x==xmax)) & class==2)
# [1] 0
# again, your results will vary

这篇关于如何使用“段"计算区域内有多少数据点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆