Saba Saba - 2 months ago 7
R Question

replacing next value with "1"

I have a matrix that contains 1565 rows and 132 columns. All the observations are either "0" or "1". Now I want to keep all the observations same but just one change, i.e whenever there is "1", the very next value in the same row should become "1". Please see below as a sample:

>df
0 0 1 0 0
NA 0 1 1 0
0 1 0 0 NA


What I want is :

0 0 1 1 0
NA 0 1 1 1
0 1 1 0 NA


I shall be thankful for your help.

Saba

Answer

One option would be using which with arr.ind=TRUE to get the row/column index, add 1 to the column index, subset the values and change it to 1.

i1 <- which(df==1, arr.ind=TRUE)
i1[,2] <- i1[,2]+1
df[i1] <- 1
df
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    0    0    1    1    0
#[2,]   NA    0    1    1    1
#[3,]    0    1    1    0   NA

If there are NA elements adjacent to 1 and want to keep it as NA, then we can modify the above code with

df[i1] <- replace(df[i1], !is.na(df[i1]), 1)

data

df <- structure(c(0L, NA, 0L, 0L, 0L, 1L, 1L, 1L, 0L, 0L, 1L, 0L, 0L, 
 0L, NA), .Dim = c(3L, 5L), .Dimnames = list(NULL, NULL))