Home > database >  Convert consecutive numbers in a R dataframe
Convert consecutive numbers in a R dataframe

Time:10-22

I have a dataframe with consecutive values, is it possible to make = 0 the numbers after 1s?

df <- data.frame(a = c(0,0,0,0,1,1,1,0,0,0),
  b = c(0,0,1,1,1,1,0,0,0,0),
  c = c(1,1,0,0,0,0,0,1,1,0))

like this:

enter image description here

CodePudding user response:

library(dplyr)
df %>% 
  mutate(across(everything(), ~  (.x == 1 & lag(.x, default = 0) != 1)))

output

   a b c
1  0 0 1
2  0 0 0
3  0 1 0
4  0 0 0
5  1 0 0
6  0 0 0
7  0 0 0
8  0 0 1
9  0 0 0
10 0 0 0

CodePudding user response:

Applying diff function may be another altarnative with BaseR,

out <- rbind(df[1,],apply(df,2,diff))
out[out!=1] <- 0 

gives,

#   a b c
#1  0 0 1
#2  0 0 0
#3  0 1 0
#4  0 0 0
#5  1 0 0
#6  0 0 0
#7  0 0 0
#8  0 0 1
#9  0 0 0
#10 0 0 0

CodePudding user response:

library(data.table)
df[] <- lapply(df, \(x) replace(x, shift(x, fill = 0) == 1, 0))
df
#    a b c
# 1  0 0 1
# 2  0 0 0
# 3  0 1 0
# 4  0 0 0
# 5  1 0 0
# 6  0 0 0
# 7  0 0 0
# 8  0 0 1
# 9  0 0 0
# 10 0 0 0

CodePudding user response:

df[-1,] <- df[-1,]*(df[-nrow(df),] == 0)
df
#>    a b c
#> 1  0 0 1
#> 2  0 0 0
#> 3  0 1 0
#> 4  0 0 0
#> 5  1 0 0
#> 6  0 0 0
#> 7  0 0 0
#> 8  0 0 1
#> 9  0 0 0
#> 10 0 0 0
  • Related