I have a dataframe as the following:
Date Bond2 Bond3 Bond5 Bond6
3218 44492 NA NA NA NA
3219 44493 NA NA NA NA
3220 44494 0.13 0.41 0.73 1.05
3221 44495 0.13 0.41 0.74 1.07
3222 44496 0.14 0.56 0.95 1.22
3223 44497 0.16 0.83 1.22 1.44
3224 44498 0.15 0.82 1.25 1.54
3225 44499 NA NA NA NA
3226 44500 NA NA NA NA
3227 44501 0.15 0.71 1.09 1.38
3228 44502 0.15 0.73 1.09 1.39
3229 44503 0.09 0.59 0.93 1.27
3230 44504 0.13 0.65 1.01 1.31
3231 44505 0.10 0.58 0.97 1.29
3232 44506 NA NA NA NA
3233 44507 NA NA NA NA
3234 44508 -0.02 0.57 0.95 1.25
I want to use the following code: data <- fill(data)
However nothing happens when I do this.
Then if I try for example data$Bond2 <- fill(data$Bond2)
, I get the error
Error in UseMethod("fill") :
no applicable method for 'fill' applied to an object of class "c('double', 'numeric')"
I do not know how to fix this? I have tried converting to character, and again nothing. Thanks.
CodePudding user response:
No need to convert to char
df <- data.frame(Date = c(4492,44493,44494,44495,44496,44497,44498,44499),
Bond2 = c(NA,NA,0.13,0.13,0.14,0.16,0.15,NA),
Bond3 = c(NA,NA,0.41,0.41,0.56,0.83,0.82,NA))
df
Date Bond2 Bond3
1 4492 NA NA
2 44493 NA NA
3 44494 0.13 0.41
4 44495 0.13 0.41
5 44496 0.14 0.56
6 44497 0.16 0.83
7 44498 0.15 0.82
8 44499 NA NA
df %>% fill(Bond2,Bond3,.direction="downup")
Output:
Date Bond2 Bond3
1 4492 0.13 0.41
2 44493 0.13 0.41
3 44494 0.13 0.41
4 44495 0.13 0.41
5 44496 0.14 0.56
6 44497 0.16 0.83
7 44498 0.15 0.82
8 44499 0.15 0.82
CodePudding user response:
We can use a pipe to feed the data to fill
, then a selection helper to select the desired columns (here starts_with
), then use the .direction
argument too.
The selection helper is very useful if we have many columns.
library(dplyr)
library(tidyr)
df %>% fill(starts_with('Bond'), .direction = 'downup')
Alternatives with other variable selections:
df %>% fill(-date, .direction = 'downup')
df %>% fill(2:200, .direction = 'downup')
df %>% fill(num_range('Bond', 1:6), .direction = 'downup')