Home > Net >  How to fill in every nth row and leave above rows with zero using dplyr?
How to fill in every nth row and leave above rows with zero using dplyr?

Time:02-26

Hi supposed I have a dataframe as such

temp <- data.frame(value = sample(c ( 1:312), 20 ), value2 = sample(c ( 1:312), 20 )  )

What I like to do is fill in every 3rd row with "hi" and leave the rest of the row above as either NA or 0. I tried doing this but

temp$t = "hi"

temp %>%
  mutate(
    prev = lag ( t, 3 )
  )

but this only works for the first 3 rows then everything is back is filled with "hi" What I want is to have "hi" only appear after every 3rd row. Ideally the first row should be "hi" as well.

thanks. enter image description here

CodePudding user response:

You may use rep -

temp$t <- rep(c('hi', NA, NA), length.out = nrow(temp))

If you prefer dplyr -

library(dplyr)

temp %>%
  mutate(t = rep(c('hi', NA, NA), length.out = n()))

#   value value2    t
#1     79    105   hi
#2    292    174 <NA>
#3     82     74 <NA>
#4    192    141   hi
#5    158    140 <NA>
#6    176    240 <NA>
#7      7     33   hi
#8     10    284 <NA>
#9     48    286 <NA>
#10    94    181   hi
#11   128     22 <NA>
#12    19    261 <NA>
#13   166    186   hi
#14   273     25 <NA>
#15   246    294 <NA>
#16   227    151   hi
#17   208    306 <NA>
#18   256    211 <NA>
#19   175    188   hi
#20   202     43 <NA>

This vector c('hi', NA, NA) is repeated until end of the data.

  • Related