【问题标题】:Filter specific column of a data.frame with also specific range [duplicate]过滤具有特定范围的data.frame的特定列[重复]
【发布时间】:2015-09-19 21:11:31
【问题描述】:

我想使用 filter() 选择 data.frame 的行。选择一行的条件是五个变量中至少有一个值应该在一个区间内。我不知道如何应用这样的条件。

我检查过类似的问题并尝试过,但没有运气! 例如 Filter each column of a data.frame based on a specific value

这是一个可重现的例子:

  xx <- rep(rep(seq(0,800,200),each=10),times=2)
  yy<-replicate(5,c(replicate(2,sort(10^runif(10,-1,0),decreasing=TRUE)),replicate(2,sort(10^runif(10,-1,0),decreasing=TRUE)), replicate(2,sort(10^runif(10,-2,0),decreasing=TRUE)),replicate(2,sort(10^runif(10,-3,0),decreasing=TRUE)), replicate(2,sort(10^runif(10,-4,0), decreasing=TRUE))))

  V <- rep(seq(100,2500,length.out=10),times=2)
  No <- rep(1:10,each=10)
  df <- data.frame(V,xx,yy,No)

我想过滤 X1:X5 列,以便在 X1 到 X5 中的任何值在 (0.5;0.55) 区间内时选择该行。

library(dplyr)

f_1 <- df%>%
filter(X1:X5>=0.5&X1:X5<=0.55)

我有错误

    Warning messages:
1: In c(0.867315118241628, 0.720280300480341, 0.673805202395872, 0.489167242541468,  :
  numerical expression has 100 elements: only the first used
2: In c(0.867315118241628, 0.720280300480341, 0.673805202395872, 0.489167242541468,  :
  numerical expression has 100 elements: only the first used
3: In c(0.867315118241628, 0.720280300480341, 0.673805202395872, 0.489167242541468,  :
  numerical expression has 100 elements: only the first used
4: In c(0.867315118241628, 0.720280300480341, 0.673805202395872, 0.489167242541468,  :
  numerical expression has 100 elements: only the first used

【问题讨论】:

  • 您希望过滤器应用的条件到底是什么?目前,X1:X5 &gt;= 0.5 &amp; X1:X5 &lt;= 0.5 等同于 X1:X5 == 0.5
  • @scoa 哦,对不起。 X1:X5 &gt;= 0.5 &amp; X1:X5 &lt;= 0.55 很好。
  • 所以你只需要在你链接的问题中调整解决方案。这里有 Marat 的回答:df%&gt;% filter(rowSums(.[,names(.) %in% paste0("X",1:5)] &gt;= 0.50 &amp; .[,names(.) %in% paste0("X",1:5)] &lt;= 0.55) == 5) 请注意,这可能会返回一个空的 data.frame,因为这是一个非常窄的窗口
  • 你的意思是X1:X5中所有值的总和应该在这个区间内?
  • 所以保留间隔中 X1:X5 中至少有一个值的每一行?然后:df%&gt;% filter(rowSums(.[,names(.) %in% paste0("X",1:5)] &gt;= 0.50 &amp; .[,names(.) %in% paste0("X",1:5)] &lt;= 0.55) &gt; 0)

标签: r dplyr


【解决方案1】:

您可以调整this answer 中提出的解决方案。它查找至少有一个值响应条件的行(因为可以对逻辑向量求和)。

filter(df,rowSums(.[,names(.) %in% paste0("X",1:5)] >= 0.50 & .[,names(.) %in% paste0("X",1:5)] <= 0.55) > 0)

【讨论】:

    猜你喜欢
    • 2018-07-03
    • 2021-07-17
    • 2022-07-27
    • 2019-12-12
    • 1970-01-01
    • 2015-03-26
    • 1970-01-01
    • 2021-11-07
    • 2018-02-16
    相关资源
    最近更新 更多