Reputation: 1
I would like to replace certain columns of a data frame with columns from another data frame if the column names match:
I extracted some numeric columns from a data.frame named train
. Then I made a second data.frame named all_box
which contain column-wise boxcox transformations of train
. After that, I want to replace those imputed data(all_box) with part of original data(train) finding by same colnames. My code was this..
I was trying to change value if the colnames are same or did not want to change any of it.
for(i in 1:length(train)){
train[,i]<-ifelse(colnames(train)[i]%in%colnames(all_box),
dplyr::select(all_box,colnames(train[i])),
dplyr::select(train,colnames(train[i])))
}
but I get the error:
Error: Unknown column
id
Callrlang::last_error()
to see a backtrace
(column 'id' is the name of first column of original data which I do not want to make any change)
Upvotes: 0
Views: 54
Reputation: 11981
the ifelse
function should not be used in this case. Try this:
train2 <- train
my_cols <- colnames(train)[colnames(train) %in% colnames(all_box)]
train2[, my_cols] <- all_box[, my_cols]
Upvotes: 0