Replace 0s with next non-zero value in column R -


someone else gave me data set looks kind of this.

input = c(0,0,0,0,1,0,0,0,0,0,0,2,0,1,0,0,2) 

what need fill 0's next non-zero number (it 1 or 2). also, next non-zero number needs filled next 1 (the last value can because going set na anyway).

so function should return this

> output =c(1,1,1,1,2,2,2,2,2,2,2,1,1,2,2,2,na) > cbind(input,output)       input output  [1,]     0      1  [2,]     0      1  [3,]     0      1  [4,]     0      1  [5,]     1      2  [6,]     0      2  [7,]     0      2  [8,]     0      2  [9,]     0      2 [10,]     0      2 [11,]     0      2 [12,]     2      1 [13,]     0      1 [14,]     1      2 [15,]     0      2 [16,]     0      2 [17,]     2     na 

thanks!

-- edited part --

the output needs array/vector (or whatever proper term in r is). example bound 2 demonstrate offset 1 filling. great answers guys

output=input[!!input][cumsum(!!input)+1] #[1]  1  1  1  1  2  2  2  2  2  2  2  1  1  2  2  2 na 

we take advantage of how r coerces numbers logicals. as.logical(0:2) return false true true. zeros become false , other numbers considered true. putting negation exclamation point in front of input coerces logical. have written as.logical(input), it's trick save few keystrokes. use logical index subset non-zero values input[!!input]. cumulative sum of logical index cumsum(!!input)+1 creates quick way index on change points when add 1 it. helps run each part separately.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -