[R] subset of obersevation depending on multiple conditions

arun smartpink111 at yahoo.com
Mon Apr 28 13:58:26 CEST 2014


Hi,

The conditions are not very clear.  Based on the rows you wanted to pick, may be this helps,

#It is better to dput() the example.

    dat <- structure(list(Date = structure(c(14610, 14611, 14612, 14613, 
14614, 14615, 14616, 14617, 14618, 14619, 14620, 14621, 14622, 
14623, 14624, 14625, 14626, 14627, 14628, 14629, 14630, 14631, 
14632, 14633, 14634, 14635, 14636, 14637, 14638, 14639), class = "Date"), 
    N = c(0, 1.9, 0, 0, 1.6, 0, 0.3, 0, 1.1, 1.7, 2.6, 0, 0, 
    0, 0, 0, 0, 0.2, 0, 0, 0, 0, 0, 0, 0, 0, 1.9, 6.2, 0, 0)), .Names = c("Date", 
"N"), row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", 
"10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", 
"21", "22", "23", "24", "25", "26", "27", "28", "29", "30"), class = "data.frame")


indx <- with(dat, N <=0.3)

rowInd <- unlist(lapply(split(seq_along(indx), cumsum(c(TRUE, diff(indx) == 1))), function(x) {
    x1 <- indx[x]
    x2 <- with(dat, N[x])
    x3 <- if (length(x2[x1]) > 1) 
        !cumsum(c(0, diff(x2[x1])) < 0)
    x[c(x3, rep(FALSE, length(x2) - length(x3)))]
}), use.names = FALSE)
rowInd
# [1]  3  4  6  7 12 13 14 15 16 17 18 29 30
dat[rowInd,]



A.K.


Hello,

I want to subset a data.frame containing the variables "Date" in (%Y %m %d
) and "N".

I want to print "Date" and "N" if  N is less than or equal to 0.3 and if
"N" is also less than or equal to 0.3 on the day before the day where "N"
is less than or equal to 0.3.

This would be the case in line 3 and 4 , 6 and 7, 12 to 18, and so on.

"Date"    "N"
"1"    2010-01-01    0
"2"    2010-01-02    1.9
"3"    2010-01-03    0
"4"    2010-01-04    0
"5"    2010-01-05    1.6
"6"    2010-01-06    0
"7"    2010-01-07    0.3
"8"    2010-01-08    0
"9"    2010-01-09    1.1
"10"    2010-01-10    1.7
"11"    2010-01-11    2.6
"12"    2010-01-12    0
"13"    2010-01-13    0
"14"    2010-01-14    0
"15"    2010-01-15    0
"16"    2010-01-16    0
"17"    2010-01-17    0
"18"    2010-01-18    0.2
"19"    2010-01-19    0
"20"    2010-01-20    0
"21"    2010-01-21    0
"22"    2010-01-22    0
"23"    2010-01-23    0
"24"    2010-01-24    0
"25"    2010-01-25    0
"26"    2010-01-26    0
"27"    2010-01-27    1.9
"28"    2010-01-28    6.2
"29"    2010-01-29    0
"30"    2010-01-30    0

I tried some methods with subset but I couldn't work it out. Maybe I have
to use something like " for (i in x) {} but as a beginner I really don't
know how to do it.

Can somebody please help me with this.

Thanks in advance,

Christoph 




More information about the R-help mailing list