找到数字列的最低价格的平均值

发布于 2025-01-22 13:37:11 字数 454 浏览 0 评论 0原文

如何找到数字列的3个最低价格的平均值(country_1)?想象一下我有数千个值?

d<-structure(list(Subarea = c("SA_1", "SA_2", "SA_3", "SA_4", "SA_5", 
"SA_6", "SA_7", "SA_8", "SA_10", "SA_9"), Country_1 = c(101.37519256645, 
105.268942332558, 100.49933368058, 104.531597221684, NA, 83.4404308144341, 
86.2833044714836, 81.808967345926, 79.6786979951661, 77.6863475527052
)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-10L))

How can I find the average of the 3 minimum prices of a numeric column (Country_1) ?Imagine that I have thousands of values?

d<-structure(list(Subarea = c("SA_1", "SA_2", "SA_3", "SA_4", "SA_5", 
"SA_6", "SA_7", "SA_8", "SA_10", "SA_9"), Country_1 = c(101.37519256645, 
105.268942332558, 100.49933368058, 104.531597221684, NA, 83.4404308144341, 
86.2833044714836, 81.808967345926, 79.6786979951661, 77.6863475527052
)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-10L))

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

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

发布评论

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

评论(3

烂人 2025-01-29 13:37:11

通过上升值,取3个第一个值并计算平均值来对矢量进行排序。

mean(head(sort(d$Country_1), 3))
# [1] 79.72467

使用sapplydplyr ::跨如果要对多列这样做:

sapply(df[, your_columns], \(x) mean(head(sort(x), 3)))

# or

library(dplyr)
d %>%
   mutate(across(your_columns, ~ mean(head(sort(.x), 3)))

Sort your vector by ascending value, take the 3 first values, and compute the mean.

mean(head(sort(d$Country_1), 3))
# [1] 79.72467

Use sapply or dplyr::across if you want to do that to multiple columns:

sapply(df[, your_columns], \(x) mean(head(sort(x), 3)))

# or

library(dplyr)
d %>%
   mutate(across(your_columns, ~ mean(head(sort(.x), 3)))
荒岛晴空 2025-01-29 13:37:11

如果您仅关心最小3个值,并且数据量较大,则使用sort()使用partial = 1:3更有效。

mean(sort(sample(d$Country_1), partial = 1:3)[1:3])

If you only care the minimal 3 values and the amount of data is large, using sort() with partial = 1:3 is more efficient.

mean(sort(sample(d$Country_1), partial = 1:3)[1:3])
乄_柒ぐ汐 2025-01-29 13:37:11

slice_min的选项

library(dplyr)
d %>% 
 slice_min(n = 3, order_by = Country_1) %>% 
 summarise(Mean = mean(Country_1))
# A tibble: 1 × 1
   Mean
  <dbl>
1  79.7

An option with slice_min

library(dplyr)
d %>% 
 slice_min(n = 3, order_by = Country_1) %>% 
 summarise(Mean = mean(Country_1))
# A tibble: 1 × 1
   Mean
  <dbl>
1  79.7
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文