gpt4 book ai didi

r - 如果我有一个包含多个列的 DataFrame,我该如何计算超过阈值的变量?

转载 作者:行者123 更新时间:2023-12-05 01:25:15 28 4
gpt4 key购买 nike

假设我有一个这样的数据框:

      variable1  variable2   variable3
2 0.58955148 0.56320222 0.98544012
3 0.33730801 0.65952594 2.27159478
4 0.99988849 2.55988180 0.34683483
5 1.47543636 0.43682811 0.71149259

我想要一个这样的函数: filter <- function(dataframe, threshold){}应用的地方可能是这样的: filter(dataframe, c(1, 1, 1)然后我返回一个新帧,它计算超过给定阈值的变量数量,如下所示:

   Variable  NbrOfExeeding  MeanOfCorrect
1 variable1 1 Mean
2 variable2 1 Mean
3 variable3 1 Mean

所以超过阈值的数据点的 nbr,以及其余的平均值。

我不确定从哪里开始。我有点知道该做什么,但不知道要使用哪些功能。遍历 variable1 并计算 amount > than threshold。2 和 3 相同。获取 variable1 的平均值,省略 number > than threshold。2 和 3 相同。进入数据框。但是,究竟如何呢?

最佳答案

可能的解决方案:

library(tidyverse)

df <- data.frame(
variable1 = c(0.58955148, 0.33730801, 0.99988849, 1.47543636),
variable2 = c(0.56320222, 0.65952594, 2.5598818, 0.43682811),
variable3 = c(0.98544012, 2.27159478, 0.34683483, 0.71149259)
)

thresholds <- c(1,1,1)

filt <- function(df, thresholds)
{
df %>%
pivot_longer(cols = everything(), names_to = "variable") %>%
group_by(variable) %>%
summarise(NbrOfExeeding = sum(value > thresholds[cur_group_id()]) ,
MeanOfCorrect = mean(value[value <= thresholds[cur_group_id()]]))
}

filt(df, thresholds)

#> # A tibble: 3 × 3
#> variable NbrOfExeeding MeanOfCorrect
#> <chr> <int> <dbl>
#> 1 variable1 1 0.642
#> 2 variable2 1 0.553
#> 3 variable3 1 0.681

关于r - 如果我有一个包含多个列的 DataFrame,我该如何计算超过阈值的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70940809/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com