假设我得到了如下所示的数据框架。我在Stackoverflow上发现的大多数建议的目的都是从one列中获取最大值,然后返回行索引。我想知道是否有一种方法可以通过扫描两个或多个列来最大限度地返回数据帧的行索引。
总之,从下面的示例中,我想得到行:
11 building_footprint_sum 0.003 0.470,它保存数据帧的最大值。
+----+-------------------------+--------------------+-------------------+
| 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 |
+----+-------------------------+--------------------+-------------------+是否有一个相当简单的方法来实现这一点?
发布于 2015-04-16 11:10:10
尝试使用pmax
?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.我建议分两步
# 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]考虑一下,如果最大值不止发生一次,则结果将有多行。
发布于 2015-04-16 11:12:00
您正在寻找矩阵达到最大值的行索引。您可以通过使用which()和arr.ind=TRUE选项来做到这一点:
> 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)。最好这样做:
> which(foo>max(foo)-0.01,arr.ind=TRUE)
row col
[1,] 1 2使用适当的小值来代替0.01。
https://stackoverflow.com/questions/29672598
复制相似问题