【问题标题】:Looking for a way to determine how many points are above a certain (nonlinear) line in R寻找一种方法来确定 R 中某条(非线性)线上方有多少点
【发布时间】:2021-11-09 11:48:55
【问题描述】:

我有一个大数据框 (df),其中包含 x/y 坐标和位于中间某处的非线性回归线,请参见下图。许多点重叠,这就是为什么我有一个额外的列 $Freq。

我正在寻找一种方法来确定这条线上方有多少点(很多在彼此之上)。请参阅下面的 df 结构。

head(df)
    x   y  Freq
    0   0  396
    1   1  222
    1   0  513
    2   0  315
    2   1  279
    2   2   36
...

我知道 StackOverflow 上的多边形方法,但我似乎无法让它们工作,部分原因可能是我的线是一系列坐标而不是公式:

head(line)
x    y
0 0.0000
1 0.4220
2 0.8350
3 1.2545
4 1.6615
5 2.0450

最后,如果我可以有三个数字,那就太好了:一个描述线上方的点数,线下方的点数,以及可能在这条特定线右侧的点数.

谢谢!

【问题讨论】:

  • 1.你的“非线性”回归线的公式在哪里,2.你对值> = 22做什么?
  • 好点,我添加了一些我想要三个数字的地方。非线性线不是公式,它是 x,y 坐标的列表

标签: r ggplot2 line polygon points


【解决方案1】:

这里有很多未知数,但是

df=merge(df,line,by="x",suffixes=c("_df","_line"))
sum(df$Freq[df$y_df>df$y_line])

[1] 537

【讨论】:

  • 非常感谢!这似乎工作得很好。使用同一行可以轻松扩展到多个 dfs 吗?
  • @tonix 也许,取决于您如何将它们存储在您的环境中。
  • 作为单独的数据框,但我们可以使用正则表达式(即 df_1、df_2 等?)
【解决方案2】:
library(tidyverse)

data <- tibble::tribble(
  ~x, ~y, ~Freq,
  0,   0,  396,
  1,   1,  222,
  1,   0,  513,
  2,   0,  315,
  2,   1,  279,
  2,   2,   36
  )
data
#> # A tibble: 6 x 3
#>       x     y  Freq
#>   <dbl> <dbl> <dbl>
#> 1     0     0   396
#> 2     1     1   222
#> 3     1     0   513
#> 4     2     0   315
#> 5     2     1   279
#> 6     2     2    36

line <- tibble::tribble(
  ~x, ~y,
  0, 0.0000,
  1, 0.4220,
  2, 0.8350,
  3, 1.2545,
  4, 1.6615,
  5, 2.0450
  )
line
#> # A tibble: 6 x 2
#>       x     y
#>   <dbl> <dbl>
#> 1     0 0    
#> 2     1 0.422
#> 3     2 0.835
#> 4     3 1.25 
#> 5     4 1.66 
#> 6     5 2.04

data %>%
  left_join(line %>% rename(line_y = y)) %>%
  filter(y > line_y)
#> Joining, by = "x"
#> # A tibble: 3 x 4
#>       x     y  Freq line_y
#>   <dbl> <dbl> <dbl>  <dbl>
#> 1     1     1   222  0.422
#> 2     2     1   279  0.835
#> 3     2     2    36  0.835

data %>%
  left_join(line %>% rename(line_y = y)) %>%
  filter(y > line_y) %>%
  summarise(sum(Freq))
#> Joining, by = "x"
#> # A tibble: 1 x 1
#>   `sum(Freq)`
#>         <dbl>
#> 1         537

data %>%
  left_join(line %>% rename(line_y = y)) %>%
  filter(y > line_y) %>%
  nrow()
#> Joining, by = "x"
#> [1] 3

reprex package 创建于 2021-11-09 (v2.0.1)

【讨论】:

  • 谢谢!!这与 user2974951 提出的方法非常相似,并且效果很好!使用同一行可以轻松扩展到多个 dfs>?
  • 是的。你也可以data &lt;- list(data1, data2, data3) %&gt;% reduce(left_join)
  • 似乎不起作用,数据丢失并删除了大量观察结果
  • 其他dfs的colnames是什么?
  • colnames(df1) % reduce(left_join) data then有 55 个观测值
猜你喜欢
  • 1970-01-01
  • 2023-04-11
  • 1970-01-01
  • 2018-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多