【发布时间】: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 >= 0.5 & X1:X5 <= 0.5等同于X1:X5 == 0.5 -
@scoa 哦,对不起。
X1:X5 >= 0.5 & X1:X5 <= 0.55很好。 -
所以你只需要在你链接的问题中调整解决方案。这里有 Marat 的回答:
df%>% filter(rowSums(.[,names(.) %in% paste0("X",1:5)] >= 0.50 & .[,names(.) %in% paste0("X",1:5)] <= 0.55) == 5)请注意,这可能会返回一个空的 data.frame,因为这是一个非常窄的窗口 -
你的意思是X1:X5中所有值的总和应该在这个区间内?
-
所以保留间隔中 X1:X5 中至少有一个值的每一行?然后:
df%>% filter(rowSums(.[,names(.) %in% paste0("X",1:5)] >= 0.50 & .[,names(.) %in% paste0("X",1:5)] <= 0.55) > 0)