Hi supposed I have a dataframe as such
temp <- data.frame(value = sample(c ( 1:312), 20 ), value2 = sample(c ( 1:312), 20 ) )
value value2
1 217 270
2 299 155
3 77 249
4 116 89
5 54 18
6 248 228
7 154 273
8 218 146
9 149 131
10 134 68
11 282 47
12 169 196
13 20 276
14 233 240
15 222 92
16 102 1
17 297 49
18 9 65
19 289 118
20 75 255
What I like to do is fill in every 3rd row with the data from value2. So for example, all rows above rows 1 & 2 would be 0 and the third row would 249, rows 5 &6 are 0 and row 7 would be 273 and so fourth.
Would be great if I can do with dplyr. thanks in advance.
CodePudding user response:
You may use if_else
-
set.seed(123)
temp <- data.frame(value = sample(c(1:312), 20), value2 = sample(c(1:312), 20))
temp %>%
mutate(value3 = if_else(row_number() %% 3 == 0, value2, 0L))
# value value2 value3
#1 179 211 0
#2 14 78 0
#3 195 81 81
#4 306 43 0
#5 118 143 0
#6 299 32 32
#7 229 109 0
#8 244 263 0
#9 311 23 23
#10 153 135 0
#11 90 224 0
#12 91 166 166
#13 256 217 0
#14 197 290 0
#15 301 69 69
#16 137 72 0
#17 26 76 0
#18 7 63 63
#19 297 141 0
#20 254 210 0