逻辑条件中的 Rollapply 百分比(R 中的滚动率)
我在 R 中有一个数据框,其中有两列,其逻辑条件如下所示:
check1 = as.logical(c(rep("TRUE",3),rep("FALSE",2),rep("TRUE",3),rep("FALSE",2)))
check2 = as.logical(c(rep("TRUE",5),rep("FALSE",2),rep("TRUE",3)))
dat = cbind(check1,check2)
结果:
check1 check2
[1,] TRUE TRUE
[2,] TRUE TRUE
[3,] TRUE TRUE
[4,] FALSE TRUE
[5,] FALSE TRUE
[6,] TRUE FALSE
[7,] TRUE FALSE
[8,] TRUE TRUE
[9,] FALSE TRUE
[10,] FALSE TRUE
我想滚动计算每列上 TRUE 的百分比,理想情况下必须如下所示:
check1 | check2 |
---|---|
1/1 | 1/1 |
2/ 2 | 2/2 |
3/3 | 3/3 |
3/4 | 4/4 |
3/5 | 5/5 |
4/6 | 5/6 |
5/7 | 5/7 |
6/8 | 6/8 |
6/9 | 7/9 |
6/10 | 8/10 |
也许...
dat%>%
mutate(cumsum(check1)/seq_along(check1))
有什么帮助吗?
I have a data frame in R with two columns with logical conditions that looks like this :
check1 = as.logical(c(rep("TRUE",3),rep("FALSE",2),rep("TRUE",3),rep("FALSE",2)))
check2 = as.logical(c(rep("TRUE",5),rep("FALSE",2),rep("TRUE",3)))
dat = cbind(check1,check2)
resulting to :
check1 check2
[1,] TRUE TRUE
[2,] TRUE TRUE
[3,] TRUE TRUE
[4,] FALSE TRUE
[5,] FALSE TRUE
[6,] TRUE FALSE
[7,] TRUE FALSE
[8,] TRUE TRUE
[9,] FALSE TRUE
[10,] FALSE TRUE
I want to roll calculate the percentage of TRUEs on each column which ideally must look like this :
check1 | check2 |
---|---|
1/1 | 1/1 |
2/2 | 2/2 |
3/3 | 3/3 |
3/4 | 4/4 |
3/5 | 5/5 |
4/6 | 5/6 |
5/7 | 5/7 |
6/8 | 6/8 |
6/9 | 7/9 |
6/10 | 8/10 |
maybe ...
dat%>%
mutate(cumsum(check1)/seq_along(check1))
Any help ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你快到了;只需使用
across
将函数应用到两列即可。或者,您可以使用 dplyr::cummean 来计算运行比例。
关于术语的说明:滚动通常是指在固定大小的窗口内计算统计数据(例如平均值或最大值)。另一方面,累积统计信息是在从索引 1(或第一行)开始的不断增加的窗口中计算的。请参阅有关窗口函数的小插图。使用正确的术语可以帮助您在文档中搜索适当的函数。
由 reprex 包 (v2.0.1)
You are almost there; just use
across
to apply your function to both columns.Alternatively, you can use
dplyr::cummean
to compute the running proportions.A note about terminology: rolling usually refers to computing a statistic (such as the mean or the max) within a fixed-size window. On the other hand, cumulative statistics are computed in an ever-increasig window starting from index 1 (or the first row). See the vignette on window functions. Using the right term may help you to search the documentation for the appropriate function.
Created on 2022-03-14 by the reprex package (v2.0.1)
1) 这给出了分数形式的结果。
1a) 要获得百分比乘以 100:
2) 或仅使用基本 R:
2a) 或百分比
1) This gives the result as fractions.
1a) To get a percentage multiply that by 100:
2) or using only base R:
2a) or as a percentage