r-创建一个带有可变阈值的特殊计数表

发布于 2025-02-13 12:08:33 字数 1108 浏览 0 评论 0原文

我有一个名为“数据”的数据框,如下所示:

ID数量
015
023
037
044
059

,我想设置阈值并计算多少个ID等于或低于该阈值,这意味着dataframe“结果”结果“结果”如:

阈值计数
10 2
03
14
25
33
74
84
95
105
发现这样做的

唯一方法是使用“ for”:

for(i在1:10) {结果$ count [i]< - nrow(数据[数据$ dentity< = i,]}

此说明确实有效。但是,有了我的真实数据,有500个阈值,我必须重复相当多 “ For”循环很长。

相同的过程12次...因此, nrow(数据[数据$ dentity< =结果$ threshold,] ,

但它不起作用(“较长的对象长度不是较短对象长度的倍数”)。 你有一些想法吗?

I have a dataframe named "data", as below :

idquantity
015
023
037
044
059

and I would like to set thresholds and count how many ids are equal or below that threshold, which means a dataframe "results" like :

thresholdcount
10
20
31
42
53
63
74
84
95
105

The only way I found to do this is to use "for" :

for(i in 1:10) {results$count[i] <- nrow(data[data$quantity <= i,]}

This instruction does work. However, with my real data, there are 500 thresholds and I have to repeat quite the same process 12 times... thus the "for" loop is very long to proceed. I couldn't find something to replace that, I would rather something like :

results$count <- nrow(data[data$quantity <= results$threshold,]

but it doesn't work ("longer object length is not a multiple of shorter object length").
Do you have some ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

删除会话 2025-02-20 12:08:33

尝试以下尝试:

library(tidyverse)

df <- tribble(
  ~id, ~quantity,
  "01", 5,
  "02", 3,
  "03", 7,
  "04", 4,
  "05", 9
)

result <- map_dfr(1:10, function(x){
  tibble(
    threshold = x,
    count = sum(df$quantity <= x)
    )
})

result
#> # A tibble: 10 × 2
#>    threshold count
#>        <int> <int>
#>  1         1     0
#>  2         2     0
#>  3         3     1
#>  4         4     2
#>  5         5     3
#>  6         6     3
#>  7         7     4
#>  8         8     4
#>  9         9     5
#> 10        10     5

在2022-07-06创建的 reprex package (v2.0.1)

Try this:

library(tidyverse)

df <- tribble(
  ~id, ~quantity,
  "01", 5,
  "02", 3,
  "03", 7,
  "04", 4,
  "05", 9
)

result <- map_dfr(1:10, function(x){
  tibble(
    threshold = x,
    count = sum(df$quantity <= x)
    )
})

result
#> # A tibble: 10 × 2
#>    threshold count
#>        <int> <int>
#>  1         1     0
#>  2         2     0
#>  3         3     1
#>  4         4     2
#>  5         5     3
#>  6         6     3
#>  7         7     4
#>  8         8     4
#>  9         9     5
#> 10        10     5

Created on 2022-07-06 by the reprex package (v2.0.1)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文