Search code examples
rfunctioncbind

R write function to bind column to dataframe


I wrote a function which creates a vector of values via a substring operation on a column of an existing data frame:

fetchParent <- function(column){
  substr(column,1,regexpr(":", column)-1)
}

An example run of this function is:

fetchParent(task2017.06.28$"Work Product")

This returns a vector:

 [1] "DE10946" "DE5909"  "US30637" "US31460" "DE16399" "DE18046" "DE18841" "DE18904" "DE19138"
 [10] "US48201" "US48314" "US48315" "US48316" "US48317 ...

I wrote a second function to bind this vector to the original data frame:

addParent <- function(df){
  df <- cbind(df,fetchParent(df$"Work Product"))
}

However, when I run this function:

addParent(task2017.06.28)

the result returns the original without the new column.

What am I missing here?


Solution

  • You have to return the new data.frame:

    addParent <- function(df){
         return(cbind(df,fetchParent(df$"Work Product")))
    }
    

    In your fetchParent() function this is not neccessary, because you don't assign the output of substr to anything.

    So this would work as well:

    addParent <- function(df){
        cbind(df,fetchParent(df$"Work Product"))
    }
    

    and also

    addParent <- function(df){
        df <- cbind(df,fetchParent(df$"Work Product"))
        return(df)
    }