Search code examples
rfill

Why does my fill function not return any values?


I am trying to fill a blanc column in R, but whenever I run the following code nothing happens:

FF5_class <- 
  FF5_class %>%
  group_by(permno) %>%
  arrange(date) %>%
  fill(Hold, .direction = "down") %>%
  ungroup()

My dataset is called: FF5_class

I have created the 'Hold' column with the following code:

FF5_class$Hold <- ifelse(FF5_class$Month == "06", FF5_class$Portfolio, "0")

A snip from my dataframe could look like this

Permno  Portfolio      Month    Hold
10026   Big.Growth       1       0
10025   Small.Value      1       0
10026   Small.Growth     2       0
10025   Big.Value        2       0
10026   Big.Value        3       0
10025   Big.Value        3       0 
10026   Small.Value      4       0
10025   Small.Growth     4       0
10026   Big. Value       5       0
10025   Small.Growth     5       0
10026   Small Value      6  Small.Value
10025   Small Growth     6  Small.Growth
10026   Small.Neutral    7       0
10025   Big.Neutral      7       0
10026   Big.Neutral      8       0
10025   Big.Neutral      8       0
10026   Big.Neutral      9       0
10025   Small.Neutral    9       0
10026   Small.Neutral   10       0
10025   Small.Neutral   10       0
10026   Small.Neutral   11       0
10025   Big.Growth      11       0
10026   Big.Growth      12       0
10025   Big.Growth      12       0

I am trying to forward fill the 'Hold' column for the value it returns. The result needs to be dependent on the respective 'Permno' codes, so there is no overlap between different firms (PERMNOs)

Can you see what I am doing wrong?

Thanks


Solution

  • fill works with NA values, instead of 0 pass NA in ifelse.

    library(dplyr)
    library(tidyr)
    
    FF5_class %>%
      mutate(Hold = ifelse(Month == "06", Portfolio, NA)) %>%
      arrange(permno, date) %>%
      group_by(permno) %>%
      fill(Hold, .direction = "down") %>%
      ungroup()