0

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)
}
dad
  • 1,335
  • 9
  • 28
  • 1
    How exactly are you calling this function? It's easier to help you if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input data so we can actually run and test the code. – MrFlick Dec 15 '17 at 21:47
  • From another function but honestly I think this is a generic case. (i.e. data.frame(name1 = c(2,3,4),name2 = c(4,5,6),name3 = c(4,5,3) ; where say fieldname = "name4" and ac_vec = c(6,5,4)) would be a fine minimal example) – dad Dec 15 '17 at 21:51
  • 1
    But are you trying to pass fieldname as a symbol? string? quosure? What are you actually passing there? – MrFlick Dec 15 '17 at 21:52
  • Trying to pass fieldname as a string. Ideally I'd like to just state straightly data$mynewname <- myvector, but I can't since data$fieldname just names the column "fieldname" verbatim instead of my parameter. – dad Dec 15 '17 at 21:57
  • Have you tried `data[[fieldname]] <- new`. (Probable duplicate.) – IRTFM Dec 16 '17 at 00:28

2 Answers2

2

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
MrFlick
  • 195,160
  • 17
  • 277
  • 295
0

Sometimes plain R is simpler.

data %>% … %>% { .[[fieldname]] <- ac_vec; . } %>% …

You can also try wrapr::let:

library(wrapr)

let(FIELDNAME=fieldname, data %>% … %>% mutate(FIELDNAME=ac_vec) %>% …)

Some nice reading about this problem and its solutions is on the wrapr authors blog.

liori
  • 40,917
  • 13
  • 78
  • 105