【问题标题】:How to print two values from a list next to each other and then find the minimum values from the printed values如何从彼此相邻的列表中打印两个值,然后从打印的值中找到最小值
【发布时间】:2021-12-27 18:03:23
【问题描述】:

我在 R 中有一个数据集列表。我正在尝试从这些列表中提取特定值以供将来使用。

我希望能够做两件事(如果可能的话)。

  1. 我希望能够在我计算并从列表中提取的值旁边的列表中打印数据集的名称。

  2. 我希望能够从该打印数据中找到最小值及其对应的数据名称。

这是一些与我已经使用的代码相似的代码,我将尝试制作一个可重现的示例:

#creating data
pressure <- runif(30, min = 3750, max = 4500)
value <- runif(30, min = 0, max = 100)
stage <- rep(c(1, 2, 3), each = 10)
raw.data <- data.frame(pressure, value, stage)


#creating my list
test_results <- purrr::pmap(data.frame(Press.Well = seq(3750, 4500, 50)),
                       ~ dplyr::filter(raw.data, pressure > ..1)) %>%
  purrr::map(. %>%
               group_by(stage) %>%
               summarize(
                 difference = (max(value) - min(value)) )
             ) %>%
  setNames(seq(3750, 4500, 50))


#made a function to view what I want to from each of the lists
print_mean <- function(list) {
  
  for (item in 1:length(list)) {    
    print(mean(test_results[[item]]$difference, na.rm = T))
  }

}

print_mean(test_results)

所以回到我正在寻找的东西:

1 - 我希望能够从列表中打印出如下内容:

Set Name in this column Mean value in this column
3750 ###
3800 ###
... ###
4500 ###

我知道我可以使用names(test_results) 获取集合的名称,并使用我创建的函数print_mean(test_results) 获取我感兴趣的值列表,但我不知道如何将它们放在一起.

还有 2 - 我想从上表中提取出最小的平均值及其对应的集合名称,例如3900 12.8(或任何可能的最小值)。但我不知道该怎么做。

任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: r list


    【解决方案1】:

    list 元素绑定在一起(bind_rows)可能更容易,然后通过mean 进行分组

    library(dplyr)
    out <- bind_rows(test_results, .id = 'Name') %>% 
        group_by(Name) %>% 
        summarise(Mean_diff = mean(difference, na.rm = TRUE))
    

    -输出

    out
    # A tibble: 15 × 2
       Name  Mean_diff
       <chr>     <dbl>
     1 3750      77.2 
     2 3800      77.2 
     3 3850      77.0 
     4 3900      62.7 
     5 3950      62.7 
     6 4000      62.7 
     7 4050      62.7 
     8 4100      62.7 
     9 4150      58.0 
    10 4200      56.4 
    11 4250      43.2 
    12 4300      43.2 
    13 4350       6.86
    14 4400       0   
    15 4450       0   
    

    然后提取min值为mean的行

    out %>%
      slice_min(n = 1, order_by = Mean_diff)
    

    或者,如果我们想使用base R - 循环使用lapplylist,提取“差异”列,获取meanstack 命名为vector 的两列数据.frame

    stack(lapply(test_results, \(x) mean(x$difference, na.rm = TRUE)))[2:1]
    

    注意:OP 没有使用set.seed,因此值将与预期输出不同

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-03
      • 1970-01-01
      • 1970-01-01
      • 2017-10-10
      相关资源
      最近更新 更多