简体   繁体   中英

subsetting the both negative and positive values in a column in R

I have a data frame in which one of the column has both negative and positive values. I want to select only those values with the below condition

only positive value less than 120 and negative value less than -90. Below is the subset of the data:

> dput(days<-head(mydata$Diff.Days,300))
c(-35L, -5L, -5L, -5L, 72L, 72L, 96L, -5L, -35L, -35L, -35L, 
-35L, -35L, -12L, -50L, -3L, -35L, -35L, -35L, 0L, -35L, -35L, 
-5L, -35L, -35L, -35L, -5L, -6L, -126L, -6L, -6L, -6L, -6L, -6L, 
-6L, 3L, -27L, 90L, -32L, -2L, -2L, -2L, -9L, -2L, -2L, -2L, 
-9L, -32L, -32L, -32L, -32L, -32L, 90L, -30L, -30L, -33L, -8L, 
-8L, -8L, 0L, 0L, 19L, -31L, -26L, -27L, 4L, 4L, 4L, -26L, -19L, 
4L, 1L, -29L, -26L, -26L, -26L, -26L, -26L, 370L, 5L, -2L, -19L, 
5L, 11L, 11L, 1L, 11L, 6L, 0L, -1L, -2L, -2L, 19L, -8L, 6L, 11L, 
-19L, -3L, -24L, -27L, -1L, 7L, -23L, 11L, 3L, 2L, 11L, 11L, 
11L, -19L, -28L, -1L, 2L, -1L, -19L, -19L, 11L, 11L, 6L, -19L, 
11L, -19L, 12L, 5L, 13L, -18L, -20L, 6L, 10L, 9L, 7L, 13L, 13L, 
7L, 95L, 4L, 4L, -11L, 7L, -7L, -8L, 11L, 8L, 10L, -20L, -32L, 
-25L, -32L, 19L, -11L, -24L, 19L, -11L, 19L, -11L, 19L, -21L, 
-12L, -12L, 18L, 11L, 18L, 5L, -15L, -11L, -11L, 19L, 19L, 12L, 
12L, -30L, -11L, -14L, -14L, 19L, 12L, -20L, -30L, 19L, -11L, 
19L, -24L, -24L, 19L, 10L, -20L, 10L, -21L, 19L, 24L, 24L, -6L, 
-6L, 13L, 26L, -4L, 19L, 19L, -37L, 24L, -6L, 21L, 14L, 21L, 
8L, 8L, 1L, 1L, -4L, -9L, 17L, 16L, 15L, -17L, -16L, -7L, 26L, 
26L, 19L, 19L, 26L, 4L, -35L, -9L, 21L, -5L, -5L, -5L, -35L, 
-35L, -35L, -35L, 26L, 19L, 19L, 26L, -5L, -5L, -5L, -5L, -5L, 
-35L, -5L, -50L, -35L, -2L, 16L, -5L, -5L, -35L, -35L, -5L, -12L, 
-12L, -12L, -12L, -12L, -12L, -12L, -12L, -12L, -12L, -12L, -12L, 
-12L, -12L, -12L, -12L, 13L, -12L, -12L, -5L, -5L, -5L, -50L, 
21L, -32L, -5L, -12L, -24L, -5L, -35L, 5L, -25L, -25L, 16L, -5L, 
-7L, -7L, -5L, 56L, 25L, 18L, 25L, 25L, 17L, -35L, -35L, -35L, 
-35L)

I tried the below code but no luck:

mydata1=mydata[mydata$Diff.Days<120 & mydata$Diff.Days>(-90)]

You have to combine the conditions with | or and not with & and .

x[(x >= 0 & x < 120) | x < -90]
#  [1]   72   72   96    0 -126    3   90   90    0    0   19    4    4    4    4
# [16]    1    5    5   11   11    1   11    6    0   19    6   11    7   11    3
#...

in case you want larger than -90.

x[x > -90 & x < 120]
#  [1] -35  -5  -5  -5  72  72  96  -5 -35 -35 -35 -35 -35 -12 -50  -3 -35 -35
# [19] -35   0 -35 -35  -5 -35 -35 -35  -5  -6  -6  -6  -6  -6  -6  -6   3 -27
#...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM