如何获得具有正值的最后一行 [英] How to get the last row number with a positive value

查看:83
本文介绍了如何获得具有正值的最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

# A tibble: 10 x 1
       a
   <dbl>
 1    1.
 2    2.
 3    3.
 4    0.
 5    5.
 6    0.
 7    7.
 8    0.
 9    0.
10    0.

如果您在第a 列中看到,第七行是最后一个行号,其值大于0(正)。我如何使R找到第七行?

If you look at column a you'll notice that the seventh row is last row number to have a value greater than 0 (positive). How do I make R find this seventh row?

换句话说,我想过滤以包括1-7行,但要排除7之后的所有行(即8-10行),因为7是最后一行正值。这是让我们开始的小动作。

In other words I want to filter to include rows 1-7, but exclude all rows after 7 (ie rows 8-10) because 7 is the last row to have a positive value. Here's the tibble to get us started.

library(tidyverse)
df <- tibble(a = c(1, 2, 3, 0, 5, 0, 7, 0, 0, 0)) %>% print()


推荐答案

一种简洁的方法是

df[1:max(which(df$a>0)),]
# A tibble: 7 x 1
#       a
#   <dbl>
# 1     1
# 2     2
# 3     3
# 4     0
# 5     5
# 6     0
# 7     7

df[1:which.max(cumsum(df$a)),]
head(df,1-which.max(rev(df$a)>0))
df[rev(cumsum(rev(df$a>0)))>0,]

花费较长的 df $ a 并比较所有方法:

Let's take a somewhat long df$a and compare all the approaches:

df <- data.frame(a = rbinom(5000, 2, 0.2) - 1)

microbenchmark(
  df[1:max(which(df$a>0)),],
  df[1:which.max(cumsum(df$a)),],
  head(df,1-which.max(rev(df$a)>0)),
  df[rev(cumsum(rev(df$a>0)))>0,],
  df[1:tail(which(sign(df$a) == 1), 1),],
  times = 10000
)
# Unit: microseconds
#                                     expr     min       lq      mean   median       uq       max neval cld
#             df[1:max(which(df$a > 0)), ]  52.817  58.5800 102.80519  62.2160  71.5910  17108.65 10000 a  
#          df[1:which.max(cumsum(df$a)), ]  36.190  40.7620  65.68274  43.0785  49.7835  18827.08 10000 a  
#   head(df, 1 - which.max(rev(df$a) > 0)) 214.812 230.7590 355.37321 249.1085 297.4340  18158.22 10000   c
#     df[rev(cumsum(rev(df$a > 0))) > 0, ] 106.391 114.6345 192.44990 124.4690 141.5650  14473.12 10000  b 
#  df[1:tail(which(sign(df$a) == 1), 1), ] 106.152 116.8985 207.69863 125.6520 150.3425 195384.36 10000  b 

这篇关于如何获得具有正值的最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆