1

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 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.