Adding column if it does not exist

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

    If you already have a dataframe with all the required columns, say

    library(tidyverse)  
    
    df_with_required_columns = 
          mtcars %>% 
          mutate(top_speed = NA_real_) %>%
          select(top_speed, mpg)
    

    then you can simply bind_rows filtering out all the rows:

    mtcars %>%
      rownames_to_column("car") %>%
      bind_rows( df_with_required_columns %>% filter(F) ) %>%
      select(car, top_speed, mpg, everything())
    

    Note that missing columns will take the type from df_with_required_columns.

提交回复
热议问题