Search code examples
rdataframedplyrlubridate

Remove values of certain months of an R Data.frame?


I have the following data.frame where i want to remove the values of certain months replace by an empty cell (Not even NA)- I tried a few different things but didn't succeed. Any help would be appreciated.

library(lubridate)
library(tidyverse)

set.seed(123)

DF <- data.frame(Date = seq(as.Date("2001-01-01"), to = as.Date("2005-12-31"), by = "day"),
                 Value = runif(1826,1,5)) %>% 
                 mutate(Year = year(Date), Month = month(Date), Day = day(Date)) %>% 
  mutate(Month %in% c(1,2,11,12), Value) <- ""

Solution

  • it can be done in this way. note that since you assigned ' ' to a numeric column, it is no longer a numeric column.

    DF <- data.frame(Date = seq(as.Date("2001-01-01"), to = as.Date("2005-12-31"), by = "day"),
                     Value = runif(1826,1,5)) 
    
    DF %>%
    mutate(Value=ifelse(month(Date)%in% c(1,2,11,12),'',Value))
    

    sample from output;

       Date       Value             
       <date>     <chr>             
     1 2001-03-10 "4.17736928444356"
     2 2005-05-28 "3.43532561417669"
     3 2004-08-10 "2.02042273338884"
     4 2004-11-04 ""                
     5 2005-04-23 "2.43464119918644"
     6 2003-07-01 "1.20879446342587"
     7 2005-08-13 "1.14129407145083"
     8 2002-01-14 ""                
     9 2001-02-19 ""                
    10 2002-07-28 "2.69385460391641"