Adding column if it does not exist

前端 未结 7 1540
粉色の甜心
粉色の甜心 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条回答
  •  -上瘾入骨i
    2020-12-15 18:16

    We could create a helper function to create the column

    fncols <- function(data, cname) {
      add <-cname[!cname%in%names(data)]
    
      if(length(add)!=0) data[add] <- NA
      data
    }
    fncols(mtcars, "mpg")
    fncols(mtcars, c("topspeed","nhj","mpg"))
    

提交回复
热议问题