Adding column if it does not exist

前端 未结 7 1537
粉色の甜心
粉色の甜心 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

    You can bind columns of the new data.frame with a fake complete data.frame filled with NA, rename the duplicated columns, and then filter only the original names.

    # your default complete vector of col names
    standard.variables = names(mtcars)
    # prep
    default=mtcars %>% mutate_all(.funs=function(x) NA)
    # treat with a data.frame missing 3 columns
    test=mtcars %>% select(-mpg, -disp, -am)
    bind_cols(test, default) %>% setNames(make.names(names(.), unique=TRUE)) %>% 
      select_(.dots=standard.variables) %>% head(2)
    ####    mpg cyl disp  hp drat    wt  qsec vs am gear carb
    #### 1  NA   6   NA 110  3.9 2.620 16.46  0 NA    4    4
    #### 2  NA   6   NA 110  3.9 2.875 17.02  0 NA    4    4
    
    0 讨论(0)
提交回复
热议问题