【问题标题】:In R: Find values in a data.frame that are below a certain threshold for each factor在 R 中:在 data.frame 中查找每个因子低于某个阈值的值
【发布时间】:2021-05-22 21:02:27
【问题描述】:

假设我有以下data.frame:

df = data.frame(groups =c("A","A","A","B","B","B","C","C","D","D","D","D","D"),
                values =c(1,1,5,3,2,1,7,7,9,8,7,6,5))

和另一个data.frame:

df_t = data.frame(groups=c("A","B","C","D"),
                  threshold=c(2,5,3,9))

现在我想在df 中添加另一列,指示这些值是否低于分组阈值 (TRUE) 或不 (FALSE)。在这种情况下:

TRUE,TRUE,FALSE,TRUE,TRUE,TRUE,FALSE,FALSE,FALSE,TRUE,TRUE,TRUE,TRUE

我知道这可以通过 for 循环轻松完成。但是,我认为必须有一种更优雅的方式来实现这一点。我也更喜欢基本 R 解决方案而不是 dplyr 或 data.table。

【问题讨论】:

    标签: r dataframe grouping threshold


    【解决方案1】:

    考虑按“组”加入数据集并创建列

    library(dplyr)
    df %>% 
       left_join(df_t) %>%
        mutate(flag = values < threshold, threshold = NULL)
    

    或者在base R中使用match得到对应的索引(或者merge

    df$flag <- with(df, values <  df_t$threshold[match(groups, df_t$groups)])
    df$flag
    #[1]  TRUE  TRUE FALSE  TRUE  TRUE  TRUE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE
    

    【讨论】:

      猜你喜欢
      • 2018-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-18
      • 2018-02-26
      • 2011-02-21
      • 2021-02-23
      相关资源
      最近更新 更多