CephBirk CephBirk - 2 months ago 6
R Question

How can I remove values from a data.frame based on logical values from another data.frame with matching indices?

I know there's a way to do this with base R or dplyr or something similar but I just can't figure this out...

I have a data.frame,

p
, with data:

TRIAL PCRIT_15min_fishMO2 PCRIT_15min_segmented PCRIT_25bins_fishMO2 PCRIT_25bins_segmented
3 Pcrit_3a 13.326 16.530 13.712 NA
33 Pcrit_38 5.610 14.832 5.568 15.091
50 Pcrit_59 NA NA 4.421 3.129


And a logical data.frame,
j
, with identical dimensions:

TRIAL PCRIT_15min_fishMO2 PCRIT_15min_segmented PCRIT_25bins_fishMO2 PCRIT_25bins_segmented
3 Pcrit_3a FALSE FALSE FALSE NA
33 Pcrit_38 FALSE FALSE FALSE FALSE
50 Pcrit_59 NA NA TRUE TRUE


I want to remove values from
p
for which the equivalent value in
j
is
FALSE
. How can I do this?

My desired result is:

TRIAL PCRIT_15min_fishMO2 PCRIT_15min_segmented PCRIT_25bins_fishMO2 PCRIT_25bins_segmented
3 Pcrit_3a NA NA NA NA
33 Pcrit_38 NA NA NA NA
50 Pcrit_59 NA NA 4.421 3.129


Here's my data:

p = structure(list(TRIAL = c("Pcrit_3a", "Pcrit_38", "Pcrit_59"),
PCRIT_15min_fishMO2 = c(13.326, 5.61, NA), PCRIT_15min_segmented = c(16.53,
14.832, NA), PCRIT_25bins_fishMO2 = c(13.712, 5.568, 4.421
), PCRIT_25bins_segmented = c(NA, 15.091, 3.129)), .Names = c("TRIAL",
"PCRIT_15min_fishMO2", "PCRIT_15min_segmented", "PCRIT_25bins_fishMO2",
"PCRIT_25bins_segmented"), row.names = c(3L, 33L, 50L), class = "data.frame")

j = structure(list(TRIAL = c("Pcrit_3a", "Pcrit_38", "Pcrit_59"),
PCRIT_15min_fishMO2 = c(FALSE, FALSE, NA), PCRIT_15min_segmented = c(FALSE,
FALSE, NA), PCRIT_25bins_fishMO2 = c(FALSE, FALSE, TRUE),
PCRIT_25bins_segmented = c(NA, FALSE, TRUE)), .Names = c("TRIAL",
"PCRIT_15min_fishMO2", "PCRIT_15min_segmented", "PCRIT_25bins_fishMO2",
"PCRIT_25bins_segmented"), row.names = c(3L, 33L, 50L), class = "data.frame")

Answer

Your answer is

p[j == FALSE] <- NA

I am sure though that your question must have been answered in some form some place else in the forum though.

Cheers