i need replace 0's 1's, groups of values meet following conditions; "1 0 1" or "0 1" (if @ beginning) or "1 0" (if @ end). given example dataframe:
df <- data.frame(a = c(1,0,1,0,1,1,1,0,1,1,1), b = c(1,1,1,0,1,1,1,0,1,1,1), c = c(1,0,1,1,1,0,1,0,1,1,1), d = c(1,1,1,0,1,1,1,1,1,1,1), e = c(1,0,1,0,1,1,1,1,1,1,1), f = c(1,1,1,1,1,1,1,1,1,0,1)) df
it need return :
df.result <- data.frame(a = c(1,1,1,0,1,1,1,0,1,1,1), b = c(1,1,1,0,1,1,1,0,1,1,1), c = c(1,1,1,1,1,1,1,0,1,1,1), d = c(1,1,1,0,1,1,1,1,1,1,1), e = c(1,1,1,0,1,1,1,1,1,1,1), f = c(1,1,1,1,1,1,1,1,1,1,1)) df.result
notice relevant 0's have changed 1's. essentially, i'm trying replace 0's occur alone in row.
any idea how achieve in r?
thanks in advance.
here solution rle()
:
foo <- function(x) { r <- rle(x) r$values[r$values==0 & r$lengths==1] <- 1 inverse.rle(r) } foo(c(0,1,0,0,1,0,1)) # testing working horse: # [1] 1 1 0 0 1 1 1
now apply function on each row , give result desired form. apply()
coerces first argument matrix:
t(apply(df, 1, foo)) # > t(apply(df,1,foo)) # [,1] [,2] [,3] [,4] [,5] [,6] # [1,] 1 1 1 1 1 1 # [2,] 1 1 1 1 1 1 # [3,] 1 1 1 1 1 1 # [4,] 0 0 1 0 0 1 # [5,] 1 1 1 1 1 1 # [6,] 1 1 1 1 1 1 # [7,] 1 1 1 1 1 1 # [8,] 0 0 0 1 1 1 # [9,] 1 1 1 1 1 1 # [10,] 1 1 1 1 1 1 # [11,] 1 1 1 1 1 1
if want dataframe result can do:
df.result <- df df.result[,] <- t(apply(df,1,foo))
Comments
Post a Comment