I have a dataset in which certain columns are dates in character form.
The dates are inconsistent in their formatting and missing data are present. I wrote a code to transform them in the correct format.
If I use the code for each column with lapply I have no issue.
When I try to implement the function to multiple columns at the same time the code gives me the following error: Error in lout[w] <- *vtmp* :
NAs are not allowed in subscripted assignments
guess_date <- function(x){
require(lubridate)
if (!is.na(x)){
result <- as.character(parse_date_time(x,
guess_formats(as.character(x), c("mdy", "dmy", "dmY")))[[1]])
}
else {result <- NA}
return(result)
}
df <- data.frame(a = c("12/01/1988","10/17/1999"),b =
c("12/01/1988",NA))
df$a <- unlist(lapply(df$a , guess_date))
df$a<- as.Date(df$a, format="%Y-%m-%d")
cols <- c("a","b")
df[,cols] <- lapply(df[,cols], function(x){
require(lubridate)
if (!is.na(x)){
result <- as.character(parse_date_time(x,
guess_formats(as.character(x), c("mdy", "dmy", "dmY")))[[1]])
}
else {result <- NA}
return(result)
})