【问题标题】:for each row in a data frame print column name that contains value less than or equal to x and calculate remaining value until next greatest value对于数据框中的每一行,打印包含小于或等于 x 的值的列名并计算剩余值,直到下一个最大值
【发布时间】:2020-03-17 03:53:56
【问题描述】:

我正在寻找一种方法来返回大于或等于 x 但小于新列中数据框每一行中的下一个最大值的第一列名称

> df <- data.frame(Loc = c("3120", "3120", "3120"), fld = c("T1", "T2", "T3"), days = c(13, 11, 18), VE = c(10,10,10), VC = c(15,15,15), V1 = c(20,20,20)
+ )
> df
   Loc fld days VE VC V1
1 3120  T1   13 10 15 20
2 3120  T2   11 10 15 20
3 3120  T3   18 10 15 20

基于 Loc 和 fld,我想获取天的值并在 VE:V1 中找到最接近的值,并在新列中打印最接近的值的列名,然后计算剩余直到下一个最大值。

  Loc fld days VE VC V1 current.growth.stage days.to.next.stage
1 3120  T1   13 10 15 20                   VE                  2
2 3120  T2   11 10 15 20                   VE                  4
3 3120  T3   18 10 15 20                   VC                  2

我已经看到多个线程使用最小值和最大值,但没有看到 df 中选择的列中的值列表以供参考。任何帮助将不胜感激!

谢谢。

机器学习

【问题讨论】:

    标签: r columnname


    【解决方案1】:

    您可以将apply 与所需的列一起使用,如下所示:

    df$current <- apply(df[3:6], 1, function(x) names(df)[3 + which.max(which(x[2:4] < x[1]))])
    df$next_stage <- apply(df[3:6], 1, function(x) (x[2:4] - x[1])[x[2:4] - x[1] > 0][1])
    df
    #>    Loc fld days VE VC V1 current next_stage
    #> 1 3120  T1   13 10 15 20      VE          2
    #> 2 3120  T2   11 10 15 20      VE          4
    #> 3 3120  T3   18 10 15 20      VC          2
    

    reprex package (v0.3.0) 于 2020-03-16 创建

    【讨论】:

      【解决方案2】:

      使用tidyverse,您可以这样做:

      library(tidyverse)
      
      df %>%
        pivot_longer(cols = c(VE, VC, V1), names_to = "stage", values_to = "stage_val") %>%
        group_by(Loc, fld) %>%
        mutate(current.growth.stage = stage[findInterval(days, stage_val)],
               next.stage = stage[findInterval(days, stage_val) + 1],
               days.to.next.stage = stage_val[stage == next.stage] - days) %>%
        filter(stage == current.growth.stage) %>%
        select(-c(stage, next.stage, stage_val)) %>%
        right_join(df)
      

      输出

      # A tibble: 3 x 8
      # Groups:   Loc, fld [3]
        Loc   fld    days current.growth.stage days.to.next.stage    VE    VC    V1
        <fct> <fct> <dbl> <chr>                             <dbl> <dbl> <dbl> <dbl>
      1 3120  T1       13 VE                                    2    10    15    20
      2 3120  T2       11 VE                                    4    10    15    20
      3 3120  T3       18 VC                                    2    10    15    20
      

      【讨论】:

        猜你喜欢
        • 2021-12-05
        • 2016-09-30
        • 2021-12-06
        • 1970-01-01
        • 1970-01-01
        • 2020-12-16
        相关资源
        最近更新 更多