Search code examples
rdataframerowna

How to turn the row values in a dataframe into NA when the values of one column are greater than another column in r?


My data looks like this:

> dput(head(CORt, 5))
structure(list(rDate = structure(c(1438019100, 1438019400, 1438019700, 
1438020000, 1438020300), class = c("POSIXct", "POSIXt"), tzone = "UTC"), 
    I630 = c(0.536, 0.506, 0.419, 0.456, 0.427), I800 = c(0.414, 
    0.388, 0.339, 0.351, 0.331), I532 = c(0.547, 0.534, 0.463, 
    0.488, 0.464), I570 = c(0.522, 0.508, 0.467, 0.468, 0.445
    ), WR630 = c(0.0127, 0.0573, 0.0083, 0.0057, 0.0053), WR800 = c(0.0144, 
    0.0506, 0.0249, 0.0163, 0.0159), WR532 = c(0.0139, 0.0394, 
    0.006, 0.005, 0.0049), WR570 = c(0.0176, 0.0379, 0.0094, 
    0.0054, 0.0049), NR630 = c(0.006, 0.034, 0.006, 0.004, 0.004
    ), NR800 = c(0.007, 0.04, 0.019, 0.02, 0.019), NR532 = c(0.007, 
    0.072, 0.01, 0.007, 0.007), NR570 = c(0.009, 0.077, 0.008, 
    0.007, 0.007), ER630 = c(0.0351, 0.0746, 0.0116, 0.0055, 
    0.0052), ER800 = c(0.0278, 0.0596, 0.03, 0.0324, 0.0303), 
    ER532 = c(0.04, 0.085, 0.013, 0.008, 0.008), ER570 = c(0.034, 
    0.083, 0.013, 0.009, 0.008)), row.names = c(NA, 5L), class = "data.frame")

In the CORt dataframe when the values of WR630 > I630 I want to turn all values of that row(s) into NA but I want to preserve the rDate column dates and the ER532 values of that row(s).

I have been using this code (example):

which(CORt$WR630>CORt$I630)
CORt[c(7632, 12530, 13684, 14260, 18295, 19735, 23770, 24634, 27529, 44055), setdiff(names(CORt), c("rDate", "ER532"))] <- NA

but this is not handy when I have 200 lines, for example. I'm looking for a code that will turn the row values when WR630 > I630 into NA directly.

Any help is much appreciated.


Solution

  • You can use the which command instead of typing output all the row numbers manually.

    CORt[which(CORt$WR630>CORt$I630),setdiff(names(CORt), c("rDate", "ER532"))] <- NA
    

    If you don't have any missing values in the data you can also skip which.

    CORt[CORt$WR630>CORt$I630,setdiff(names(CORt), c("rDate", "ER532"))] <- NA