Search code examples
rgeospatialdplyrnse

Using 'mutate' with passed in parameter name to create new column


I'd like to add a new data column and name the column using a parameter I pass in. I'm used to using dplyr's mutate line-by-line and other methods that directly hard-code the name, but I'm unsure where to start here. How would I use mutate or something similarly simple/elegant?

Reproducible example:

Suppose main is a dataframe defined by

main <- data.frame(name1 = c(2,3,4), name2 = c(4,5,6), name3 = c(4,5,3))  

And fieldname is a string parameter with "name4" passed in and new is c(6,5,4)

I want to tack fieldname and new onto main for final dataframe

    name1 name2 name3 name4
1     2     4     4     6
2     3     5     5     5
3     4     6     3     4  

but the below function does not work like that yet.

joinData <- function(main, new, fieldname) {
    main$fieldname <- new  # This does not work; Want my string variable's 
                           # contents to become my new column name, 
                           # not my variable's name "fieldname"
    return(main)
}

Solution

  • With your sample, use

    dd <- data.frame(name1 = c(2,3,4), name2 = c(4,5,6), name3 = c(4,5,3))  
    joinData <- function(main, new, fieldname) {
        main[[fieldname]] <- new 
        return(main)
    }
    # joinData(dd, letters[1:3], "letters")
    #   name1 name2 name3 letters
    # 1     2     4     4       a
    # 2     3     5     5       b
    # 3     4     6     3       c