[英]Count last rows that meet a criteria in R
I'm trying to make a counter that adds the last rows that meet a criteria.我正在尝试制作一个计数器来添加符合条件的最后一行。 When this criterion is not met, the counter must stop.当不满足此标准时,计数器必须停止。
Let me explain:让我解释:
Take this df
拿这个df
df = data.frame(a = c(1,4,3,6,5,3,5,6,2,6,7,1,4,5,7),
b = c(1,5,5,4,8,5,1,4,8,1,5,4,8,7,6),
c = c(4,5,5,8,6,1,4,8,5,5,1,5,1,4,7))
I just want to sum this values that meet x > 3
in the last rows:我只想对最后几行中满足x > 3
的值求和:
So, the result must be:所以,结果必须是:
i made a code that does this but in a slow way:我编写了一个代码来执行此操作,但速度很慢:
df = data.frame(a = c(1,4,3,6,5,3,5,6,2,6,7,1,4,5,7),
b = c(1,5,5,4,8,5,1,4,8,1,5,4,8,7,6),
c = c(4,5,5,8,6,1,4,8,5,5,1,5,1,4,7))
df_with_results = data.frame("a" = NA,
"b" = NA,
"c" = NA)
n_line = 0
count = 0
for(i in 1:ncol(df)){ #loop for each column
for(k in 0:nrow(df)){ #loop for each row
if(df[(nrow(df)-k), i] > 3) {
count = count + 1
} else {
break
}
}
df_with_results[1,i] = count
count = 0 #column change
}
any tips?有小费吗?
thanks谢谢
We can use rle
here我们可以在这里使用rle
library(dplyr)
sapply(df, \(x) with(rle(x > 3), last(lengths)[last(values)])[1])
a b c
3 5 2
One way:单程:
df = data.frame(a = c(1,4,3,6,5,3,5,6,2,6,7,1,4,5,7),
b = c(1,5,5,4,8,5,1,4,8,1,5,4,8,7,6),
c = c(4,5,5,8,6,1,4,8,5,5,1,5,1,4,7))
sapply(df, \(x) match(T, rev(x) <= 3, length(x) + 1) - 1)
#> a b c
#> 3 5 2
Another way:其它的办法:
sapply(df, \(x) sum(cumprod(rev(x)>3)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.