i have r dataframe created sqlite database table. data has many date time columns character columns. mass convert them date columns in dataframe.
i can 1 column @ time this:
loan$maturity <- as.date(gsub(', 12:00:00 am', '', loan$maturity), "%m/%d/%y")
i can mass update for columns factors. every column date value contains
i <- sapply(loan, is.factor) loan[i] <- lapply(loan[i], as.character)
how can grab every column contains text ", 12:00:00 am" , change fields using function as.date() converts character values date value.
this solution assumes (as @tim asking) single instance of , 12:00:00 am
in column constitutes conversion.
i supply 2 versions check , conversion. first uses vapply
find columns convert, , converts them in lapply
. second version check , conversion in single lapply
.
#create dummy data.frame df <- data.frame(a=1, b='1/1/92, 12:00:00 am') #check columns have ', 12:00:00 am' in them convertcols <- vapply(df, function(col) sum(grepl(', 12:00:00 am', col)) > 0, logical(1)) #convert columns contained ', 12:00:00 am' using conversion function df[convertcols] <- lapply(df[convertcols], function(dates) as.date(gsub(', 12:00:00 am', '', dates), "%m/%d/%y")) #create dummy data.frame df <- data.frame(a=1, b='1/1/92, 12:00:00 am') #done in single lapply df[] <- lapply(df[], function(col) { if(sum(grepl(', 12:00:00 am', col)) > 0) as.date(gsub(', 12:00:00 am', '', col), "%m/%d/%y") else col })
if every element in column must contain , 12:00:00 am
constitute conversion check switch sum(grepl(', 12:00:00 am', col)) == length(col)
opposed sum(grepl(', 12:00:00 am', col)) > 0
Comments
Post a Comment