【问题标题】:Figuring out the max value from a series of columns in R从R中的一系列列中找出最大值
【发布时间】:2022-06-22 21:58:13
【问题描述】:

对于每个观察,都有三个音量值,volume_1、volume_2 和 volume_3。有时volume_1 最大,有时volume_3 最大。虽然我觉得这段代码应该很简单,但是如何计算volume_1最大,volume_2最大,然后volume_3最大的时间的整体百分比。

这是我的一些数据

structure(list(PVC = c("29A", "2D5", "2HX", "38A", "3CN", "6021051"
), Age = c(6, 5, 6, 10, 5, 7), volume_1 = c(59.44244884, 51.69518257, 
63.17950819, 56.4269955, 64.05189184, 61.82983473), volume_2 = c(54.74897726, 
56.64778447, 51.86880673, 59.71146472, 58.96633234, 63.39471043
), volume_3 = c(58.97596791, 51.75711362, 61.36142512, 57.09629745, 
64.25164825, 63.19407463), Year = c("2003", "2002", "2003", "2008", 
"2003", "1994"), averageAB = c(57.09571305, 54.17148352, 57.52415746, 
58.06923011, 61.50911209, 62.61227258), diff_AB_C = c(-1.88025486, 
2.4143699, -3.83726766, 0.972932659999998, -2.74253616, -0.58180205
), sumAB = c(114.1914261, 108.34296704, 115.04831492, 116.13846022, 
123.01822418, 125.22454516), ratioAB_C = c(1.93623657477333, 
2.09329615703558, 1.87492899154491, 2.03408041163622, 1.91463141461122, 
1.98158681637776)), row.names = c(NA, 6L), class = "data.frame")

一如既往地感谢您的帮助!!

【问题讨论】:

标签: r


【解决方案1】:

可能有更简单的方法,但我会使用 tidyverse

df %>% 
  rowwise() %>%
  mutate(max = case_when(max(volume_1, volume_2, volume_3) == volume_1 ~ "volume_1",
                         max(volume_1, volume_2, volume_3) == volume_2 ~ "volume_2",
                         max(volume_1, volume_2, volume_3) == volume_3 ~ "volume_3") %>% 
  ungroup() %>%
  count(max)

【讨论】:

    【解决方案2】:

    使用max.col() 函数很容易做到这一点:

    df$highest_col <- max.col(df[,3:5])
    
    head(df)
          PVC Age volume_1 volume_2 volume_3 Year averageAB
    1     29A   6 59.44245 54.74898 58.97597 2003  57.09571
    2     2D5   5 51.69518 56.64778 51.75711 2002  54.17148
    3     2HX   6 63.17951 51.86881 61.36143 2003  57.52416
    4     38A  10 56.42700 59.71146 57.09630 2008  58.06923
    5     3CN   5 64.05189 58.96633 64.25165 2003  61.50911
    6 6021051   7 61.82983 63.39471 63.19407 1994  62.61227
       diff_AB_C    sumAB ratioAB_C highest_col
    1 -1.8802549 114.1914  1.936237           1
    2  2.4143699 108.3430  2.093296           2
    3 -3.8372677 115.0483  1.874929           1
    4  0.9729327 116.1385  2.034080           2
    5 -2.7425362 123.0182  1.914631           3
    6 -0.5818020 125.2245  1.981587           2
    

    然后您可以在该新列上运行 table() 以获取计数。

    【讨论】:

      猜你喜欢
      • 2023-03-08
      • 2015-11-28
      • 1970-01-01
      • 2021-05-17
      • 2017-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-08
      相关资源
      最近更新 更多