Adding column if it does not exist
If you had an empty dataframe that contains all the names to check for, you can use bind_rows
to add columns.
I used purrr:map_dfr
to make the empty tibble
with the appropriate column names.
columns = c("top_speed", "mpg") %>%
map_dfr( ~tibble(!!.x := logical() ) )
# A tibble: 0 x 2
# ... with 2 variables: top_speed <lgl>, mpg <lgl>
bind_rows(columns, mtcars)
# A tibble: 32 x 12
top_speed mpg cyl disp hp drat wt qsec vs am gear carb
<lgl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 NA 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
2 NA 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
3 NA 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
You can use the rowwise
function like this :
library(tidyverse)
mtcars %>%
tbl_df() %>%
rownames_to_column("car") %>%
rowwise() %>%
mutate(top_speed = ifelse("top_speed" %in% names(.), top_speed, NA),
mpg = ifelse("mpg" %in% names(.), mpg, NA)) %>%
select(car, top_speed, mpg, everything())
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))])
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"))