| Start |
|---|
| Identifying and grouping by runs in base R One might want to group their data by the runs of a variable and perform some sort of analysis. Consider the following simple dataset: The variable In base R, we would first compute the run-length encoding of the The next step is to compute the run number of each row of our dataset. We know that the total number of runs is Now we can use |
Run-length Encoding with rle Run-length encoding captures the lengths of runs of consecutive elements in a vector. Consider an example vector: The The values for each run are captured in This captures that we first saw a run of 1's, then a run of 2's, then a run of 3's, then a run of 1's, and so on. The lengths of each run are captured in We see that the initial run of 1's was of length 1, the run of 2's that followed was of length 3, and so on. |
| Run-length encoding to compress and decompress vectors Long vectors with long runs of the same value can be significantly compressed by storing them in their run-length encoding (the value of each run and the number of times that value is repeated). As an example, consider a vector of length 10 million with a huge number of 1's and only a small number of 0's: Storing 10 million entries will require significant space, but we can instead create a data frame with the run-length encoding of this vector: From the run-length encoding, we see that the first 52,818 values in the vector are 1's, followed by a single 0, followed by 219,329 consecutive 1's, followed by a 0, and so on. The run-length encoding only has 207 entries, requiring us to store only 414 values instead of 10 million values. As Decompressing a vector in run-length encoding can be accomplished in two ways. The first method is to simply call We can confirm that our decompressed data is identical to our original data: The second method is to use R's built-in We can confirm again that this produces exactly the original |
| Identifying and grouping by runs in data.table The data.table package provides a convenient way to group by runs in data. Consider the following example data: The variable The data.table One can then easily group on this run ID and summarize the RemarksA run is a consecutive sequence of repeated values or observations. For repeated values, R's "run-length encoding" concisely describes a vector in terms of its runs. Consider: We have a length-one run of 1s; then a length-three run of 2s; then a length-one run of 3s; and so on. R's run-length encoding captures all the lengths and values of a vector's runs. ExtensionsA run can also refer to consecutive observations in a tabular data. While R doesn't have a natural way of encoding these, they can be handled with |
Read Article
https://develop.horje.com/learn/1434/reference