代码之家  ›  专栏  ›  技术社区  ›  Stefan

基于不大于且不小于R的过滤器或子集

  •  0
  • Stefan  · 技术社区  · 5 年前

    ?'>' 没有什么比 !> !>= !between() dplyr !(x[x >= left & x <= right]) 不起作用。。。

    require(dplyr)
    #> Loading required package: dplyr
    #> 
    #> Attaching package: 'dplyr'
    #> The following objects are masked from 'package:stats':
    #> 
    #>     filter, lag
    #> The following objects are masked from 'package:base':
    #> 
    #>     intersect, setdiff, setequal, union
    require(ggplot2)
    #> Loading required package: ggplot2
    x <- seq(-5, 5, length.out = 1000)
    d <- tibble(X = x, Y = x^3)
    
    ### THIS WORKS
    (d %>% 
      filter(!between(X, -2, 2)) -> d_sub)
    #> # A tibble: 600 x 2
    #>        X     Y
    #>    <dbl> <dbl>
    #>  1 -5    -125 
    #>  2 -4.99 -124.
    #>  3 -4.98 -124.
    #>  4 -4.97 -123.
    #>  5 -4.96 -122.
    #>  6 -4.95 -121.
    #>  7 -4.94 -121.
    #>  8 -4.93 -120.
    #>  9 -4.92 -119.
    #> 10 -4.91 -118.
    #> # ... with 590 more rows
    
    ### PLOT TO CONFIRM
    (d_sub%>% 
      ggplot(aes(X,Y)) + geom_point())
    

    于2020-01-30由 reprex package (第0.3.0版)

    1 回复  |  直到 5 年前
        1
  •  1
  •   dww Jarretinha    5 年前

    不需要否定任何东西。你能做到的 (x <= -2) | (x >= 2)

    例如。

    X= -10:10
    
    X[(X <= -2) | (X >= 2)]
    #[1] -10  -9  -8  -7  -6  -5  -4  -3  -2   2   3   4   5   6   7   8   9  10
    

    这和

    X[!(X >-2 & X <2)]
    #[1] -10  -9  -8  -7  -6  -5  -4  -3  -2   2   3   4   5   6   7   8   9  10
    
        2
  •  1
  •   akrun    5 年前

    base R ,我们可以使用 subset 并只指定不带引号的列名

    d_sub2 <- subset(d, !(X >=-2 & X <2))
    identical(d_sub, d_sub2)
    #[1] TRUE
    

    [

    d_sub3 <- d[!(d$X >= -2 & d$X < 2),]