我的数据是这样的:
X1e X2e X3e X4e
360 0 0 0
360 0 0 0
260 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
90 0 0 0
360 0 360 0
360 0 360 260
我要删除0到270之间的X1e X4e列,没有删除0行
for (i in c(1,4)){
e <- assign(paste("X",i, "e",sep = ""),i)
dat <- dat[with(dat, !((e>0)&(e<270))), ]
}
这将删除我所有的dat,而我的dat变成了空。我的问题在哪里?
答案 0 :(得分:2)
Base R解决方案:
read
OR
使用dat[!(dat$X1e>0 & dat$X1e<270) & !(dat$X4e>0 & dat$X4e<270),]
:
sqldf
输出:
library(sqldf)
sqldf("select * from dat where X1e not between 1 AND 270 AND X4e not between 1 AND 270")
答案 1 :(得分:2)
创建感兴趣的列名
cidx <- paste0("X", c(1, 4), "e")
对每列执行逻辑操作
test <- !(df[,cidx] > 0 & df[,cidx] < 270)
各行的总和(逻辑“与”),以查找所有列均为TRUE
的行
ridx <- rowSums(test) == length(cidx)
子集原始数据。
df[ridx,]
答案 2 :(得分:1)
喜欢吗?
library(tidyverse)
df<-read.table(text="X1e X2e X3e X4e
360 0 0 0
360 0 0 0
260 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
90 0 0 0
360 0 360 0
360 0 360 260",header=T)
df%>%
filter_at(vars(X1e,X4e), all_vars(.<=0 | .>270))
X1e X2e X3e X4e
1 360 0 0 0
2 360 0 0 0
3 0 0 0 0
4 0 0 0 0
5 0 0 0 0
6 360 0 360 0
答案 3 :(得分:1)
另一个解决方案。
我通常不喜欢subset
,因为它使用非标准评估,而且速度很慢,但是进展顺利。
subset(df, (X1e <= 0 | X1e >= 270) & (X4e <= 0 | X4e >= 270))
# X1e X2e X3e X4e
#1 360 0 0 0
#2 360 0 0 0
#4 0 0 0 0
#5 0 0 0 0
#6 0 0 0 0
#8 360 0 360 0