这是我正在处理的数据集的一个可重复的小例子:
set.seed(123)
dat <- as.data.frame( cbind(a=1+round(runif(5), 2), b=round(rnorm(5), 2), high_cutoff=round(1+rnorm(5), 1)) )
Run Code Online (Sandbox Code Playgroud)
数据框是:
a b high_cutoff
1.29 -1.69 2.3
1.79 1.24 -0.7
1.41 -0.11 2.7
1.88 -0.12 1.5
1.94 0.18 3.5
Run Code Online (Sandbox Code Playgroud)
我试图通过行检查前两列中是否至少有一个值高于第三列中的correpondig阈值(假设我想存储1,如果这两个值中的任何一个更高那么截止).
在这个例子中,我期望找到的是:
higher_than_cutoff
0
1
0
1
0
Run Code Online (Sandbox Code Playgroud)
我一直在尝试使用以下(错误)代码及其中的一些变体,但没有取得多大成功:
higher_than_cutoff <- apply( dat[, c("a", "b")], 1, function(x) any(x > dat[, "high_cutoff"]) )
Run Code Online (Sandbox Code Playgroud)
能否就如何进行提出一些建议?任何帮助都非常感谢
这是一个可能的矢量化解决方案(如果你没事,TRUE/FALSE你可以+在开头删除它)
+(rowSums(dat[-3L] > dat[, 3L]) > 0)
## [1] 0 1 0 1 0
Run Code Online (Sandbox Code Playgroud)
如果你坚持apply,你可以做点什么
apply(dat, 1, function(x) +(any(x[-3] > x[3])))
## [1] 0 1 0 1 0
Run Code Online (Sandbox Code Playgroud)
你可以试试
as.integer(do.call(pmax,dat[-3]) > dat[,3])
#[1] 0 1 0 1 0
Run Code Online (Sandbox Code Playgroud)
要么
((max.col(dat))!=3)+0L
#[1] 0 1 0 1 0
Run Code Online (Sandbox Code Playgroud)