User Tools

Site Tools


documents:111012rtricks

This is an old revision of the document!


R Tricks

removing trailing zeros from a vector

When you import data from the out put of other software, you might have trailing 0s at the end of each column:

> d0
 [1] 69.444 70.889 86.667 95.667 83.444 78.333 67.889
 [8] 56.000 49.222 40.333 37.889 31.889 30.333 26.667
[15] 22.444 23.111 20.889 22.000 20.111 19.778 20.778
[22] 19.667 17.333 19.333 19.000 16.333 14.444 13.889
[29] 18.000 21.778 23.556 23.889 28.778 40.000 48.667
[36] 55.889 66.667 78.889 72.222 84.778 68.778 69.444
[43]  0.000  0.000  0.000  0.000  0.000  0.000  0.000
[50]  0.000  0.000  0.000  0.000  0.000  0.000  0.000
[57]  0.000  0.000  0.000  0.000  0.000  0.000  0.000
[64]  0.000  0.000  0.000  0.000

To remove them, there could be many ways, but here is my one liner.

d0c <- d0[rev(cumsum(rev(d0)))>0]

Then the output is

> d0c
 [1] 69.444 70.889 86.667 95.667 83.444 78.333 67.889
 [8] 56.000 49.222 40.333 37.889 31.889 30.333 26.667
[15] 22.444 23.111 20.889 22.000 20.111 19.778 20.778
[22] 19.667 17.333 19.333 19.000 16.333 14.444 13.889
[29] 18.000 21.778 23.556 23.889 28.778 40.000 48.667
[36] 55.889 66.667 78.889 72.222 84.778 68.778 69.444
documents/111012rtricks.1318432340.txt.gz · Last modified: 2016/05/24 12:46 (external edit)

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki