0
votes

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)
}
2
How exactly are you calling this function? It's easier to help you if you provide a reproducible example with sample input data so we can actually run and test the code. - MrFlick
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
But are you trying to pass fieldname as a symbol? string? quosure? What are you actually passing there? - MrFlick
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
Have you tried data[[fieldname]] <- new. (Probable duplicate.) - IRTFM

2 Answers

2
votes

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
0
votes

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.