Creating a dataframe using declared variables

I'm trying to create a dataframe to assist in downstream calculations. All "MineralVars" need an NA value in this 1-row dataframe. MineralVars will always change in length and variable names, so I can't create the dataframe by inputting each Mineral one at a time. I need to create it using the string 'MineralVars'.

# Declare variables
MineralVars <- c("Al", "Cu", "Pb")


# Create helper dataframe
Placeholder_df <- data.frame(make = "Placeholder", modelid = "Placeholder",
                             unitno = "Placeholder", compart = "Placeholder",
                             MineralVars = NA, meterread = NA, order = NA)

My desired dataframe would look like this;

Desired_df <- data.frame(sampledate = NA, make = "Placeholder", modelid = "Placeholder",
                            unitno = "Placeholder", compart = "Placeholder", oilchanged = "Placeholder",
                            Cu = NA, Pb = NA, Al = NA, meterread = NA, order = NA)

1 answer

  • answered 2020-02-17 00:35 akrun

    We can just do an assignment

    Placeholder_df[MineralVars] <- NA
    

    and remove the "MineralVars"

    Placeholder_df["MineralVars"] <- NULL
    

    Or use add_column

    library(tibble)
    library(dplyr)
    add_column(Placeholder_df,.before = "MineralVars", 
        !!!setNames(rep(NA,length(MineralVars)), MineralVars))  %>%
          mutate(MineralVars = NULL)
     #      make     modelid      unitno     compart Al Cu Pb meterread order
    #1 Placeholder Placeholder Placeholder Placeholder NA NA NA        NA    NA
    

    and assign (<-) it either 'Placeholder_df' or a new object