Adding column if it does not exist

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

    You can use the rowwise function like this :

    library(tidyverse)
    mtcars %>%
      tbl_df() %>%
      rownames_to_column("car") %>%
      rowwise() %>%
      mutate(top_speed = ifelse("top_speed" %in% names(.), top_speed, NA),
             mpg = ifelse("mpg" %in% names(.), mpg, NA)) %>%
      select(car, top_speed, mpg, everything())
    

提交回复
热议问题