Adding column if it does not exist

前端 未结 7 1553
粉色の甜心
粉色の甜心 2020-12-15 17:37

I have a bunch of data frames with different variables. I want to read them into R and add columns to those that are short of a few variables so that they all have a common

7条回答
  •  我在风中等你
    2020-12-15 18:16

    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 , mpg 
    
    bind_rows(columns, mtcars)
    
    # A tibble: 32 x 12
       top_speed   mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
                      
     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
    

提交回复
热议问题