My goal is to extend a large dataframe with 200'000 columns in the following way:
I have a list of names in a specific order and I want to extend my original dataframe that has some rownames in common with this list of names such that the extended dataframe has a column with entries exactly as in the list of names and wherever values are missing in the dataframe it should have zeroes.
Minimal reproducible example:
entities<-c("C1","C3","C4","C5","E1","E2")
list_of_names<-data.frame(entities)
df<-data.frame(matrix(runif(30), nrow = 3, ncol = 10))
rownames(df)<-c("E1", "C1","C4")
> df
X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
E1 0.6228159 0.0744723 0.34010018 0.5720812 0.3179460 0.2405663696 0.6198333 0.9367545 0.95729614 0.10671495
C1 0.2435715 0.4046881 0.01714992 0.7806331 0.1113826 0.0003340805 0.1747583 0.5234170 0.07591773 0.76162701
C4 0.3804787 0.8364844 0.85255672 0.8909652 0.0665782 0.7447360640 0.3022620 0.2111203 0.72338528 0.04510692
My current way to do it is the following:
df_extended<-merge(list_of_names,df,by="entities", all.x=TRUE)
df_extended[is.na(df_extended)] <- 0
> df_extended
entities X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
1 C1 0.2435715 0.4046881 0.01714992 0.7806331 0.1113826 0.0003340805 0.1747583 0.5234170 0.07591773 0.76162701
2 C3 0.0000000 0.0000000 0.00000000 0.0000000 0.0000000 0.0000000000 0.0000000 0.0000000 0.00000000 0.00000000
3 C4 0.3804787 0.8364844 0.85255672 0.8909652 0.0665782 0.7447360640 0.3022620 0.2111203 0.72338528 0.04510692
4 C5 0.0000000 0.0000000 0.00000000 0.0000000 0.0000000 0.0000000000 0.0000000 0.0000000 0.00000000 0.00000000
5 E1 0.6228159 0.0744723 0.34010018 0.5720812 0.3179460 0.2405663696 0.6198333 0.9367545 0.95729614 0.10671495
6 E2 0.0000000 0.0000000 0.00000000 0.0000000 0.0000000 0.0000000000 0.0000000 0.0000000 0.00000000 0.00000000
My problem is, that this approach takes too much time to run it for a dataframe having 200'000 columns. So I would appreciate ideas on alternative approaches to speed it up. Thanks for any help!