Create new columns by multiplying some columns in dataframe by single column

I want to generate multiple new columns by multiplying some columns in a dataframe by a single column in R and append the new columns to the original df.

I have the initial data formatted as follows

ID  amount  supplier_1  supplier_2   supplier_3 ... supplier_100
1   10       0               1            0             0
1   15       1               0            0             0
1   20       1               0            0             0
2    5       0               0            0             1
2    8       0               1            0             0
2   10       0               0            0             1

#I have more than 100 suppliers in this df.

What I want to have as output is to multiply all supplier_n columns (dummy vars) by amount.

ID  amount  supplier_1  supplier_2   supplier_3 ... supplier_100  
1   10       0               1            0             0                 
1   15       1               0            0             0                 
1   20       1               0            0             0                 
2    5       0               0            0             1                 
2    8       0               1            0             0                 
2   10       0               0            0             1                 


amt*supplier_1   amt*supplier_2  amt*supplier_3 ..... amt*supplier_100   Total_amt 
 0               10               0                      0                 45 
15                0               0                      0                 45
20                0               0                      0                 45
 0                0               0                      5                 23
 0                8               0                      0                 23
 0                0               0                     10                 23


#total_amt is the sum of amount conditional on ID. 

I find a similar here and tried the mutate_all with function(col) commands but did not work

Multiply all columns in dataframe by single column.

Would greatly appreciate it if any one can provide some suggestions!

Leave a Comment