r - replacing next value with "1" -
i have matrix contains 1565 rows , 132 columns. observations either "0" or "1". want keep observations same 1 change, i.e whenever there "1", next value in same row should become "1". please see below sample:
>df 0 0 1 0 0 na 0 1 1 0 0 1 0 0 na
what want :
0 0 1 1 0 na 0 1 1 1 0 1 1 0 na
i shall thankful help.
saba
one option using which
arr.ind=true
row/column index, add 1 column index, subset values , change 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 na elements adjacent 1 , want keep na, can modify 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))
Comments
Post a Comment