Search code examples
rdplyrdatasetiteration

How to transfer a column from a dataset sharing the same one with another one


I have two versions of datasets sharing the same columns (more or less). Let's take as an example

db = airquality
db1 = airquality[,-c(6)]
db1$Ozone[db1$Ozone < 30] <- 24
db1$Month[db1$Month == 5] <- 24

db
db1

If I would like to transfer two columns 'Ozone' and 'Wind' from the dataset 'db1' to the 'db' dataset by writing a code using the pipe operator %>% or another iterative method to achieve this result, which code you may possibly suggest?

Thanks


Solution

  • You csn do:

    library(dplyr)
    
    db1 %>% 
      select(Ozone, Wind) %>% 
      bind_cols(db)
    

    Note that in this example, since some column names will be duplicated in the final result, dplyr will automatically rename the duplicates by appending numbers to the end of the column names.