![](/img/trans.png)
[英]How to get a new column in a data frame which has only elements which appear in the set more than once in R
[英]In R, how can one detect consecutive data points within a column of data which have a value >y only when they appear more than x times consecutively?
我是R的初學者,並且試圖找到一種方法來檢測值大於等於y的數據列中的x個連續值。 示例:查找所有4個或更多連續數據點的值> = 2的實例
運行長度編碼rle()命令看起來很有希望識別這些連續值:
rle(dataset>=2)
但是我無法找到一種方法來進一步設置長度為> = 4和值為“ TRUE”的條件。
有什么建議么?
res <- rle(dataset>=2)
which( res$lengths>=4 & res$values==TRUE] )
這將在rle
結果的壓縮表示中識別它們,然后您將需要擴展該結果並為序列選擇起點。
您可以簡單地轉換向量,並在其上使用rle:
res = rle(runif(1000, 0, 4) >= 2)
res
Run Length Encoding
lengths: int [1:491] 2 2 2 2 3 1 3 2 7 1 ...
values : logi [1:491] TRUE FALSE TRUE FALSE TRUE FALSE ...
要獲取運行在向量中的位置的索引,可以使用以下技巧:
res$values = res$lengths > 4
inv_res = inverse.rle(res)
seq_along(inv_res)[inv_res]
[1] 3 4 5 6 7 8 9 10 11 12 13 37 38 39 40 41 42 74
[19] 75 76 77 78 79 80 81 82 83 84 85 108 109 110 111 112 142 143
[37] 144 145 146 147 148 221 222 223 224 225 226 235 236 237 238 239 240 241
[55] 278 279 280 281 282 305 306 307 308 309 310 311 312 313 314 315 316 317
[73] 318 319 342 343 344 345 346 347 414 415 416 417 418 419 430 431 432 433
[91] 434 435 449 450 451 452 453 472 473 474 475 476 477 478 523 524 525 526
[109] 527 545 546 547 548 549 561 562 563 564 565 566 567 568 569 607 608 609
[127] 610 611 612 613 625 626 627 628 629 630 646 647 648 649 650 651 652 699
[145] 700 701 702 703 765 766 767 768 769 770 771 772 773 789 790 791 792 793
[163] 794 795 800 801 802 803 804 810 811 812 813 814 850 851 852 853 854 855
[181] 869 870 871 872 873 879 880 881 882 883 904 905 906 907 908 909 919 920
[199] 921 922 923 949 950 951 952 953 954 955 956 957 958 959 960 961
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.