W作者celestialgod (天)
看板Statistics
标题Re: [程式] 关於R 统计点的数目
时间Thu Dec 31 01:31:27 2015
※ 引述《jackhzt (巴克球)》之铭言:
: [软体程式类别]:R
: [程式问题]:资料处理
: [程式熟悉]:熟悉
: [问题叙述]:假设我有一笔资料(x1,y1),(x2,y2),(x3,y3)...我将其用plot打点
: 如今想对其所在的座标做分割,切出4个等面积的区域,
: 请问有相关的程式码可以统计区域内点的总数目吗?
: [程式范例]:
: EX:
: x=rnorm(10,0,1)
: y=rnorm(10,2,1)
: z=data.frame(x,y)
: plot(z) #打点出来
: 假设现在想对x轴=0以及y轴=0 分四块,
: 那有方法可以统计这4块面积中点的数目吗?
: 目前我的方法就是 把点拿出来先对x轴比大小 再对y轴比大小
: 但是如果比数或是需要分割的东西太多,就会很复杂,有其他较好的方法吗?
1. 如果会dplyr
library(dplyr)
library(magrittr)
set.seed(2)
x=rnorm(10,0,1)
y=rnorm(10,1,1)
z=data.frame(x,y)
a = 0; b = 0
z_append = z %>% mutate(x_gt_a = x > a, y_gt_b = y > b) %>%
group_by(x_gt_a, y_gt_b) %>% summarise(count = length(x))
#
# Source: local data frame [4 x 3]
# Groups: x_gt_a y_gt_b
#
# x_gt_a y_gt_b count
# (lgl) (lgl) (int)
# 1 FALSE FALSE 1
# 2 FALSE TRUE 4
# 3 TRUE FALSE 1
# 4 TRUE TRUE 4
# 多个切割点就看第三点吧
2. 如果不会dplyr
mat = tapply(rep(1, nrow(z)), list(z$x > a, z$y > b), length)
z_count = data.frame(x_gt_a = rep(colnames(mat), 2),
y_gt_b = rep(rownames(mat), each = 2), count = as.vector(mat))
# x_gt_a y_gt_b count
# 1 FALSE FALSE 1
# 2 TRUE FALSE 1
# 3 FALSE TRUE 4
# 4 TRUE TRUE 4
3. findInterval
library(dplyr)
library(magrittr)
set.seed(2)
x=rnorm(1000,0,1)
y=rnorm(1000,1,1)
z=data.frame(x = x, y = y)
x_cutPoints = c(-Inf, seq(-1, 1, by = 0.1), Inf)
y_cutPoints = c(-Inf, seq(-1, 1, by = 0.1), Inf)
count_df = z %>% mutate(cutPointsGroup_x = cut(x, x_cutPoints),
cutPointsGroup_y = cut(y, y_cutPoints)) %>%
group_by(cutPointsGroup_x, cutPointsGroup_y) %>%
summarise(count = length(x))
#
# Source: local data frame [276 x 3]
# Groups: cutPointsGroup_x, cutPointsGroup_y
#
# cutPointsGroup_x cutPointsGroup_y count
# (fctr) (fctr) (int)
# 1 (-Inf,-1] (-Inf,-1] 3
# 2 (-Inf,-1] (-1,-0.9] 2
# 3 (-Inf,-1] (-0.8,-0.7] 1
# 4 (-Inf,-1] (-0.7,-0.6] 4
# 5 (-Inf,-1] (-0.6,-0.5] 2
# 6 (-Inf,-1] (-0.5,-0.4] 2
# 7 (-Inf,-1] (-0.4,-0.3] 4
# 8 (-Inf,-1] (-0.3,-0.2] 2
# 9 (-Inf,-1] (-0.2,-0.1] 2
# 10 (-Inf,-1] (-0.1,0] 6
# .. ... ... ...
--
R资料整理套件系列文:
magrittr #1LhSWhpH (R_Language) http://tinyurl.com/1LhSWhpH
data.table #1LhW7Tvj (R_Language) http://tinyurl.com/1LhW7Tvj
dplyr(上) #1LhpJCfB (R_Language) http://tinyurl.com/1LhpJCfB
dplyr(下) #1Lhw8b-s (R_Language)
tidyr #1Liqls1R (R_Language) http://tinyurl.com/1Liqls1R
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 140.109.73.231
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Statistics/M.1451496691.A.D63.html
1F:推 jackhzt: 谢谢你! 12/31 01:43
2F:→ jackhzt: 上面的方法很实用 但是我的问题可能没有问得很好 12/31 01:43
3F:→ jackhzt: 因为其实我不只是切4块 是希望可以将plot上的座标 12/31 01:44
切的多块一点的话,我要再想想看XD
4F:→ jackhzt: 全部分割成固定长宽的正方格 在统计所有方格内点的数量 12/31 01:45
5F:→ jackhzt: 如果这样有好的方法吗? 谢谢你之前的解答~ 12/31 01:47
请看第三点
6F:推 jackhzt: 刚刚发现电脑越来越高 原来是我跪下来了 谢谢大大~ 12/31 02:00
另外,如果要改成矩阵,可以找reshape2:::dcast, tidyr:::spread or
data.table:::dcast.data.table
※ 编辑: celestialgod (140.109.73.231), 12/31/2015 02:09:43
7F:推 jackhzt: 谢谢大大的提点 太感谢了 12/31 02:20