【问题标题】:How can I use the R function to find max value of particular attribute based on some condition如何使用 R 函数根据某些条件查找特定属性的最大值
【发布时间】:2021-06-02 07:48:44
【问题描述】:

就像我有一个数据集 enter image description here

那么我怎样才能找到第一局的最高得分

【问题讨论】:

  • max(df[df$innings=="1",]$score)。假设 df 是您的数据集。

标签: r


【解决方案1】:

你可以的

df <- data.frame(innings=c(1,1,2,2,1), score = c(170,189,230,190,210))

inningsScoreSplit <- split(df$score,df$innings)

maxScores <- data.frame(
  inning = names(inningsScoreSplit),
  maxScore = sapply(inningsScoreSplit,max)
)

得到

> maxScores
  inning maxScore
1      1      210
2      2      230

【讨论】:

    【解决方案2】:

    这是学习 tidyverse 的好机会。 基本上你可以用一行代码做到这一点:

    # This make your dataset
    df <- data.frame(innings=c(1,1,2,2,1), score = c(170,189,230,190,210)) 
    
    # This loads up the library tidyverse. 
    # If this gives you an error you might need to install tidyverse by using "install.packages("tidyverse")"
    library(tidyverse) 
    
    # This calculates the max. There are 2 commands here: filter and summarise.
    Result <- df %>% filter(innings == 1) %>% summarise(max(score)) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-20
      • 1970-01-01
      • 2019-10-02
      • 2019-05-22
      • 2020-06-11
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      相关资源
      最近更新 更多