How to insert new column names to a tibble in r?

Viewed 80

I have the following Tibbles.

tmp             <- tibble()
tmp2            <- tibble()
tmp             <- tmp %>% rbind( colSums( y_matrix) ) 
tmp2            <- tmp2 %>% rbind( proportions( colSums( y_matrix )))
data          <- bind_cols(tmp,tmp2)

I want to add column names for "data" accordingly. The number of columns in tmp and tmp2 will change from time to time. So how can I add column names without defining them one by one?

The expected column names in the output is like this.

c1 c2 c1_prop c2_prop

Is there any method to create this?

1 Answers

I don't have enough reputation to comment this data.table solution, which you could could always send to as_tibble(). If this wasn't what you were after, could you put an explicit example of the data and expected output?

library(data.table)
setDT(data)

setnames(data, ncol(tmp)+(1:ncol(tmp2)), paste0(names(tmp),"_prop"))

However, wouldn't it just be better to name the columns correctly before merging?

Related