首页 > 解决方案 > 如何在矩阵中找到特定给定值的行和列?

问题描述

我有一份关于 NBA 10 名球员的得分和比赛数据。

我想找出从 2005 年到 2014 年篮球场均得分最高的人,并编写了以下代码:

为了找到每个球员的 PPG,我这样写:

Points
P<-round(Points/Games,2)
P

要找到最高的 PPG,

M<-max(P,na.rm=T)

得到 35.4 的输出

现在,我只看矩阵就知道这是科比布莱恩特。但是如何编写代码来获取该元素的行和列呢?

数据来源:超数据科学

标签: rmatrixrows

解决方案


欢迎来到堆栈溢出。下次尝试包含示例数据。它可以帮助我们帮助您。她是使用该dplyr软件包的解决方案。它是tidyverse方言的一部分R。如果您只是在学习R,请安装 Tidyverse 软件包套件。它会是你最好的朋友。

data <- data.frame(points = c(10, 12, 12, 4), 
                   games = c(2, 3, 2, 1), 
                   dude = c("a", "b", "c", "d"))

library(dplyr) 
theDude <- data %>%  #start with the data above and pipe it to the next line
    mutate(pointsPerGame = points/games) %>%   # create the average variable and pipe to next line
    filter(pointsPerGame == max(pointsPerGame)) %>%  # keep only the record(s) with the largest average and pipe to the next line
    select(dude) # keep the person's name

推荐阅读