Forklift17
Forklift17

Reputation: 2477

Setting the data type of columns from a CSV file of just headers

library(dplyr)
library(purrr)

tbl1 <- tibble(data.frame(
  a = c(1,2),
  b = c(3,4)
))

tbl2 <- c('a','b','c','d') %>% purrr::map_dfc(
  setNames, object = list(numeric()))

I want to add all the rows of tbl1 to tbl2, with columns that are in tbl2 and not tbl1 as NA. So the tbl would look like this:

a b c  d
1 3 NA NA
2 4 NA NA

How do I do this without having to manually list columns c and d?

Upvotes: 0

Views: 58

Answers (2)

akrun
akrun

Reputation: 887153

Another option is rbindlist

library(data.table)
rbindlist(list(tbl1, tbl2))

Upvotes: 0

bcarlsen
bcarlsen

Reputation: 1441

  1. dplyr::bind_rows is useful for this.
> bind_rows(tbl1, tbl2)
# A tibble: 2 x 4
      a     b     c     d
  <dbl> <dbl> <dbl> <dbl>
1     1     3    NA    NA
2     2     4    NA    NA
  1. You can define a tbl_df object directly with tibble(). You do not need to do tibble(data.frame(<values>)). A tbl_df is basically just a data.frame with a fancy print method and some (external) grouping support.
  2. Similarly, you can define an empty tbl directly: tibble(a = numeric(), b = numeric(), c = numeric(), d = numeric())

Upvotes: 1

Related Questions