I'm trying to create a new column within a function. Basically, I want to use a function to create a new field, based on an old field (using string searching). Having no luck:
old_field <- c("September 2012", "September 2012")
case_id <- c("1","1")
my_df <- data.frame(case_id, old_field)
old_date_to_new_date <- function(df, new_date, old_date) {
df[[new_date]][grepl('Sep', old_date, ignore.case = TRUE)] <- '09-01' #if 'sep' found in old date field, put "09-01" in new date field.
df[[new_date]][grepl('2012', old_date, ignore.case = TRUE)] <- paste('2012-',new_date,sep='')# add year to new date field
}
old_date_to_new_date (my_df,"new_field","old_field")
The function runs just fine, but fails to add the new column to the dataframe. I've tested this and I can't even modify anything within the dataframe using the function. Code works fine outside of the function and does what expected. I've tried adding a return(df) statement within the function but still no luck.