Filtering data frame based on values in second data frame

Viewed 1775

I have 2 data frames:

at1 = data.frame(ID = c("A", "B", "C", "D", "E"), Sample1 = rnorm(5, 50000, 2500),
      Sample2 = rnorm(5, 50000, 2500), Sample3 = rnorm(5, 50000, 2500),
      row.names = "ID")

  Sample1  Sample2  Sample3
A 52626.55 51924.51 50919.90
B 51430.51 49100.38 51005.92
C 50038.27 52254.73 50014.78
D 48644.46 53926.53 51590.05
E 46462.01 45097.48 50963.39

bt1 = data.frame(ID = c("A", "B", "C", "D", "E"), Sample1 = c(0,1,1,1,1),
      Sample2 = c(0,0,0,1,0), Sample3 = c(1,0,1,1,0), 
      row.names = "ID")

   Sample1 Sample2 Sample3
A       0       0       1
B       1       0       0
C       1       0       1
D       1       1       1
E       1       0       0

I would like to filter every cell in at1 based on the value in the corresponding cell in bt1 (0 or 1) and have the result stored in a new data frame ct1. For instance, if bt1[1, "Sample1"] = 1 then ct1[1, "Sample1"] = at1[1, "Sample1"]. If bt1[1, "Sample1"] = 0 then ct1[1, "Sample1"] = 0. My original data frames have more than 100 columns and more than 30,000 rows.

I was wondering if there is an easier way than writing if-loops (e.g. using "apply"?).

3 Answers
Related