Adding column if it does not exist

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

    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))])
    

提交回复
热议问题