0

I have an XTS data frame of zeros, 1's and -1's and I want to change the only the first zero value after the numbers to the value of this number for example if the column is

0,0,0,1,1,1,**0**,0,0 

I want it to be as

0,0,0,1,1,1,**1**,0,0 

and if it is

0,0,0,-1,-1,**0**,0

I want it to be

0,0,0,-1,-1,**-1**,0

thanks in advance

  • Please do not post an image of code/data/errors: it cannot be copied or searched (SEO), it breaks screen-readers, and it may not fit well on some mobile devices. Ref: https://meta.stackoverflow.com/a/285557 (and https://xkcd.com/2116/). Please just include the code, console output, or data (e.g., `data.frame(...)` or the output from `dput(head(x))`) directly. – r2evans Dec 07 '20 at 12:42
  • ok thanks for telling – hisham saad Dec 07 '20 at 19:39

1 Answers1

0

Here's a dplyr method:

library(dplyr)
dat <- tibble(
  int1 = c(0,0,0,1,1,1,0,0,0),
  int2 = c(0,0,0,-1,-1,0,0,0,0)
)

dat %>%
  mutate_at(vars(int1, int2), ~ if_else(. == 0 & lag(. != 0, default = FALSE) != 0, lag(.), .))
# # A tibble: 9 x 2
#    int1  int2
#   <dbl> <dbl>
# 1     0     0
# 2     0     0
# 3     0     0
# 4     1    -1
# 5     1    -1
# 6     1    -1
# 7     1     0
# 8     0     0
# 9     0     0

If you need these as additional columns (vice in-place replacement):

dat %>%
  mutate_at(vars(int1, int2), list(fixed = ~ if_else(. == 0 & lag(. != 0, default = FALSE) != 0, lag(.), .)))
# # A tibble: 9 x 4
#    int1  int2 int1_fixed int2_fixed
#   <dbl> <dbl>      <dbl>      <dbl>
# 1     0     0          0          0
# 2     0     0          0          0
# 3     0     0          0          0
# 4     1    -1          1         -1
# 5     1    -1          1         -1
# 6     1     0          1         -1
# 7     0     0          1          0
# 8     0     0          0          0
# 9     0     0          0          0
r2evans
  • 141,215
  • 6
  • 77
  • 149
  • nice solution but what if my data is an XTS object – hisham saad Dec 07 '20 at 19:34
  • I know that's what you say you have, but you haven't provided sample data, so I worked with what I knew (which was very little). Please read my first comment about `dput`. – r2evans Dec 07 '20 at 19:57