r - Push values to the left, replace NAs with zeros -


i have kind of data.frame

mydata <- data.frame(matrix(seq(20*3), 5, 6))  mydata[1,1:3] <-  na  mydata[2,1:1] <-  na  mydata[2,4] <-  na  mydata[3,1:3] <-  na  mydata[3,5:6] <-  na  mydata[4,2:4] <-  na  mydata[5,1:2] <-  na  

that looks this:

userid    x1    x2    x3    x4    x5    x6 1         na    na    na    16    21    26 2         na    7     12    na    22    27  3         na    na    na    18    na    na 4         4     na    na    na    24    29 5         na    na    15    20    25    30 

i run code locates first non na value, , pushes sequence there, , replaces na 0. data going this:

userid    x1    x2    x3    x4    x5    x6 1         16    21    26     0     0     0 2         7     12     0    22    27     0 3         18     0     0     0     0     0 4         4      0     0     0    24    29 5         15    20    25    30     0     0 

we can use apply margin=1 loop on rows, identify index of first non-na value ('i1'), values index end of vector, concatenate rest na, replace na 0, transpose output , assign dataset.

mydata[-1] <-  t(apply(mydata[-1], 1, function(x) {                       i1 <- which(!is.na(x))[1]                       x1 <- c(x[i1:length(x)], rep(na, i1-1))                       replace(x1, is.na(x1), 0)                 })) mydata #  userid x1 x2 x3 x4 x5 x6 #1      1 16 21 26  0  0  0 #2      2  7 12  0 22 27  0 #3      3 18  0  0  0  0  0 #4      4  4  0  0  0 24 29 #5      5 15 20 25 30  0  0 

data

mydata <- cbind(userid=1:5, mydata) 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -