John Smith John Smith - 24 days ago 7
R Question

R Combine columns in one dataframe with another while removing old columns

I have a main data frame where i have created new columns based on old columns

I created subsets of the main data frame for these columns initially and performed some transformations and now wish to merge the columns back removing the old columns in the process

The old columns in the main data frame are called

rev_quest_7
and
rev_quest_5
and contain 7 columns and five columns respectively

The new columns I created from the previous columns are called
updated_7
and
updated_5
and contain the same amount of columns and data

All four are data frames.

mydf_calc <- mydf%>%
select(everything(), -rev_quest_7, -rev_quest_5) %>%
bind_cols(updated_7, updated_5)


In the end I wish to merge the data frames
updated_7
and
updated_5
main frames
rev_quest_7
,
rev_quest_5
from the main data frame creating a new data frame called
mydf_calc
. All four five items in this question are data frames

Thank you for your help

Answer

One way to do this is to use select_ to programmatically specify the columns to remove using the column names from data frames rev_quest_7 and rev_quest_5:

library(dplyr)
mydf_calc <- mydf %>% select_(.dots=paste0("-",unique(c(colnames(rev_quest_7),colnames(rev_quest_5))))) %>%
                      bind_cols(update_7,update_5)

I will illustrate with a simple example where rev_quest_7 and rev_quest_5 only have 2 columns from mydf, but that should not matter:

mydf <- data.frame(a=1:3,b=2:4,c=3:5,d=4:6,e=5:7)
##  a b c d e
##1 1 2 3 4 5
##2 2 3 4 5 6
##3 3 4 5 6 7
## rev_quest_7 extracts columns "a" and "c"
rev_quest_7 <- mydf[,c(1,3)]
## rev_quest_5 extracts columns "b" and "d"
rev_quest_5 <- mydf[,c(2,4)]
## update_7 and update_5 operates on rev_quest_7 and rev_quest_5, respectively
update_7 <- 2 * rev_quest_7
##  a  c
##1 2  6
##2 4  8
##3 6 10
update_5 <- 3 * rev_quest_5
##   b  d
##1  6 12
##2  9 15
##3 12 18

mydf_calc <- mydf %>% select_(.dots=paste0("-",unique(c(colnames(rev_quest_7),colnames(rev_quest_5))))) %>%
                      bind_cols(update_7,update_5)
##  e a  c  b  d
##1 5 2  6  6 12
##2 6 4  8  9 15
##3 7 6 10 12 18