首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何根据R中数据帧的最大值从数据帧返回行?

如何根据R中数据帧的最大值从数据帧返回行?
EN

Stack Overflow用户
提问于 2015-04-16 10:55:44
回答 2查看 158关注 0票数 0

假设我得到了如下所示的数据框架。我在Stackoverflow上发现的大多数建议的目的都是从one列中获取最大值,然后返回行索引。我想知道是否有一种方法可以通过扫描两个或多个列来最大限度地返回数据帧的行索引。

总之,从下面的示例中,我想得到行:

代码语言:javascript
复制
11 building_footprint_sum 0.003 0.470

,它保存数据帧的最大值。

代码语言:javascript
复制
+----+-------------------------+--------------------+-------------------+
| id |        plot_name        | rsquare_allotments | rsquare_block_dev |
+----+-------------------------+--------------------+-------------------+
|  6 | building_footprint_max  | 0.002              | 0.421             |
|  7 | building_footprint_mean | 0.002              | 0.354             |
|  8 | building_footprint_med  | 0.002              | 0.350             |
|  9 | building_footprint_min  | 0.002              | 0.278             |
| 10 | building_footprint_sd   | 0.003              | 0.052             |
| 11 | building_footprint_sum  | 0.003              | 0.470             |
+----+-------------------------+--------------------+-------------------+

是否有一个相当简单的方法来实现这一点?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-04-16 11:10:10

尝试使用pmax

代码语言:javascript
复制
?pmax    
pmax and pmin take one or more vectors (or matrices) as arguments and
return a single vector giving the ‘parallel’ maxima (or minima) of the vectors.

我建议分两步

代码语言:javascript
复制
# make a new column that compares column 3 and column 4 and returns the larger value
> df$new <- pmax(df$rsquare_allotments, df$rsquare_block_dev)

# look for the row, where the new variable has the largest value
> df[(df$new == max(df$new)), ][3:4]

考虑一下,如果最大值不止发生一次,则结果将有多行。

票数 0
EN

Stack Overflow用户

发布于 2015-04-16 11:12:00

您正在寻找矩阵达到最大值的行索引。您可以通过使用which()arr.ind=TRUE选项来做到这一点:

代码语言:javascript
复制
> set.seed(1)
> foo <- matrix(rnorm(6),3,2)
> which(foo==max(foo),arr.ind=TRUE)
     row col
[1,]   1   2

因此,在这种情况下,您需要第1行(并且可以丢弃col输出)。

如果你走这条路,要小心浮点算法和== (见FAQ 7.31)。最好这样做:

代码语言:javascript
复制
> which(foo>max(foo)-0.01,arr.ind=TRUE)
     row col
[1,]   1   2

使用适当的小值来代替0.01。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29672598

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档