代码之家  ›  专栏  ›  技术社区  ›  string

在R中计算数据帧中每组的和和和最小最大值

  •  0
  • string  · 技术社区  · 8 年前

    我有一个下面的示例数据框

    df <- data.frame("Group"= c(1,1,2,2,2),"H" = 
    c("H1","H3","H3","H4","H2"), "W1" = c(95, 0, 0,0,50) , "W2" = c(0, 
    95,95, 0,85),"W3" = c(85, 50,50 ,95,0))
    

    需要计算两个额外指标: 第一个度量:基于该组的w1、w2、w3的每个组和行,如果w1、w2和w3的值等于或大于85,则输出为100%。 例如:对于第2组,对于W2和W3,最大值等于85以上。 对于w1,它小于85,所以结果是 66.7条

    第二个度量:该组的W1、W2、W3列的最大行最小值。例如:对于组2,min(max[0 0 50]、max[95 0 85]、max[50 95 0])= 50个

    DesiredDf <- data.frame("Group"= c(1,1,2,2,2),"H" =     
    c("H1","H3","H3","H4","H2"), "W1" = c(95, 0, 0,0,50) , 
    "W2" = c(0, 95,95, 0,85), "W3" = c(85, 50,50 ,95,0),
    "W" = c(100,100,66.7 ,66.7,66.7),MINMAX = c(85,85,50,50,50))
    

    已经尝试了for循环和sapply方法,但是实际数据集太大,执行太慢。正在寻找在R中更无缝地计算这些度量的方法。

    2 回复  |  直到 8 年前
        1
  •  0
  •   tmfmnk    8 年前

    通过使用 dplyr

    df %>% 
      group_by(Group) %>% 
      mutate(w = rowMeans(cbind(max(W1) >= 85, max(W2) >= 85, max(W3) >= 85)),
             minmax = min(max(W1), max(W2), max(W3)))
    
    # A tibble: 5 x 7
    # Groups:   Group [2]
      Group H        W1    W2    W3     w minmax
      <dbl> <fct> <dbl> <dbl> <dbl> <dbl>  <dbl>
    1    1. H1      95.    0.   85. 1.00     85.
    2    1. H3       0.   95.   50. 1.00     85.
    3    2. H3       0.   95.   50. 0.667    50.
    4    2. H4       0.    0.   95. 0.667    50.
    5    2. H2      50.   85.    0. 0.667    50.
    
        2
  •  2
  •   DanY    8 年前

    data.table方式:

    # use data.table
    library(data.table)
    setDT(df)
    
    # aggregate data by group in order to calculate the 2 desired metrics
    df1 <- df[ , .(maxw1 = max(W1), maxw2 = max(W2), maxw3 = max(W3)), by=Group]
    
    # calculate the metrics
    df1[ , metric1 := rowMeans(cbind(maxw1>=85, maxw2>=85, maxw3>=85))]
    df1[ , metric2 := do.call(pmin,.SD), .SDcols = c("maxw1", "maxw2", "maxw3")]
    
    # merge metrics back on to original dataframe
    df <- merge(df, df1[ , .(Group, metric1, metric2)], by="Group")