Home > Software engineering >  as.Date(paste(t$date, '01'), '%Y %B %d') return NA in R?
as.Date(paste(t$date, '01'), '%Y %B %d') return NA in R?

Time:05-25

I want to change t$date to date format. But the as.Date() function returns NA.

NOTE: The column date is extracted from another dataframe, so the column order should not be rearranged to the normal month sequence (Jan - Dec) as the column will be binded to another dataframe later, the current months orderd should be kept.

Any thoughts and ideas, please?

I have tried the code below:

 # extract lyr names and time
> lyr_names <- names(idw2) %>% 
    as_tibble() %>% 
    separate(value , into =  c("date", "method"), sep = "_") 
Warning message:
Expected 2 pieces. Additional pieces discarded in 240 rows [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...]. 
> lyr_names
# A tibble: 240 x 2
   date     method
   <chr>    <chr> 
 1 Apr 1998 masked
 2 Apr 1999 masked
 3 Apr 2000 masked
 4 Apr 2001 masked
 5 Apr 2002 masked
 6 Apr 2003 masked
 7 Apr 2004 masked
 8 Apr 2005 masked
 9 Apr 2006 masked
10 Apr 2007 masked
# ... with 230 more rows
> 
> t <- lyr_names %>% select(date)
> 
> # create date
> t$date <- as.Date(paste(t$date, '01'), '%Y %B %d')
> t 
# A tibble: 240 x 1
   date  
   <date>
 1 NA    
 2 NA    
 3 NA    
 4 NA    
 5 NA    
 6 NA    
 7 NA    
 8 NA    
 9 NA    
10 NA    

CodePudding user response:

Your date format mask is off. Use this version:

t$date <- as.Date(paste(t$date, '01'), '%B %Y %d')
  •  Tags:  
  • r
  • Related