Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiply columns/rows in one R dataset with values from another

Tags:

dataframe

r

I have the two following datasets:

Dataset1                                 Dataset2

Kingdom  P1  P2  P5  P6  P7  T4  T6      P1  P2  P5  P6  P7  T4  T6
Virus    5   4   4   5   5   3   3       3   4   4   2   1   1   6
Bacteria 3   3   4   6   1   2   1       
Animal   1   2   3   4   4   1   5     
etc.                                 

I need to multiply every column of dataset1 by the corresponding values in dataset2. For example the value for P1 in dataset2 needs to multiply every row of the P1 column in dataset1 by 3. What I am showing here it's just an excerpt of my data. Dataset1 has thousands of inputs.

If those two datasets get multiplied, the output would look something like this:

Kingdom  P1  P2  P5  P6  P7  T4  T6                    
Virus    15  16  16  10   5   3  18                      
Bacteria 9   12  16  12   1   2   6       
Animal   3   8   12   8   4   1  30     
etc. 

Any ideas on how to tackle this would be greatly appreciated! Thank you.

like image 973
Pablita Avatar asked Dec 03 '22 11:12

Pablita


1 Answers

We can use mapply to multiply each column from Dataset1 and Dataset2. Dataset2 is the final output.

Dataset3 <- Dataset1
Dataset3[, -1]<- mapply(`*`, Dataset1[, -1], Dataset2)
Dataset3
#    Kingdom P1 P2 P5 P6 P7 T4 T6
# 1    Virus 15 16 16 10  5  3 18
# 2 Bacteria  9 12 16 12  1  2  6
# 3   Animal  3  8 12  8  4  1 30

DATA

Dataset1 <- read.table(text = "Kingdom  P1  P2  P5  P6  P7  T4  T6
Virus    5   4   4   5   5   3   3       
Bacteria 3   3   4   6   1   2   1       
Animal   1   2   3   4   4   1   5",
                       header = TRUE, stringsAsFactors = FALSE)

Dataset2 <- read.table(text = "P1  P2  P5  P6  P7  T4  T6
                       3   4   4   2   1   1   6",
                       header = TRUE)
like image 133
www Avatar answered Jan 17 '23 15:01

www