Adding column if it does not exist

Solution 1:

Another option that does not require creating a helper function (or an already complete data.frame) using tibble's add_column:

library(tibble)

cols <- c(top_speed = NA_real_, nhj = NA_real_, mpg = NA_real_)

add_column(mtcars, !!!cols[setdiff(names(cols), names(mtcars))])

Solution 2:

We could create a helper function to create the column

fncols <- function(data, cname) {
  add <-cname[!cname%in%names(data)]

  if(length(add)!=0) data[add] <- NA
  data
}
fncols(mtcars, "mpg")
fncols(mtcars, c("topspeed","nhj","mpg"))