[SOLVED] Unable to create a new column using a function in R

Issue

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.

Solution

We need to return the data along with get the value of the column using [[

old_date_to_new_date <- function(df, new_date, old_date) {
     i1 <- grepl('Sep', df[[old_date]], ignore.case = TRUE)
     i2 <- grepl('2012', df[[old_date]], ignore.case = TRUE)
     df[[new_date]][i1] <- '09-01' #if 'sep' found in old date field, put "09-01" in new date field. 
     df[[new_date]][i2] <- paste('2012-',df[[new_date]][i2],sep='')# add year to new date field
     df
    }
    

old_date_to_new_date (my_df,"new_field","old_field")
#   case_id      old_field  new_field
#1       1 September 2012 2012-09-01
#2       1 September 2012 2012-09-01

NOTE: If we need to update the original object, assign the output back to the original object

my_df <- old_date_to_new_date (my_df,"new_field","old_field")

Answered By – akrun

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *