检查数据帧行中的至少一个值是否大于给定的行特定阈值
checking whether at least one value in a dataframe row is bigger than a given row-specific threshold
这是我正在处理的数据集的小型可重现示例:
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)) )
数据帧是:
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
我正在尝试按行检查前两列中是否至少有一个值高于第三列中的相应阈值
(假设如果两个值中的任何一个高于截止值,我想存储一个 1)。
在示例中,我希望找到的是:
higher_than_cutoff
0
1
0
1
0
我一直在尝试使用以下(错误的)代码及其一些变体,但没有取得多大成功:
higher_than_cutoff <- apply( dat[, c("a", "b")], 1, function(x) any(x > dat[, "high_cutoff"]) )
能否就如何进行提供一些建议?
非常感谢任何帮助
这是一个可能的矢量化解决方案(如果您只使用 TRUE/FALSE
就可以,您可以删除开头的 +
)
+(rowSums(dat[-3L] > dat[, 3L]) > 0)
## [1] 0 1 0 1 0
如果你坚持apply
,你可以这样做
apply(dat, 1, function(x) +(any(x[-3] > x[3])))
## [1] 0 1 0 1 0
可以通过
获得所需的输出
higher_than_cutoff <- apply(dat,1,function(x) (max(x[1],x[2])>x[3])*1)
你可以试试
as.integer(do.call(pmax,dat[-3]) > dat[,3])
#[1] 0 1 0 1 0
或者
((max.col(dat))!=3)+0L
#[1] 0 1 0 1 0
也许我误解了你想要实现的目标,但无需使用 apply
即可获得所需的输出,我们只比较完整的列向量,不需要按行操作。
+(dat$a > dat$high_cutoff | dat$b > dat$high_cutoff)
# [1] 0 1 0 1 0
这是我正在处理的数据集的小型可重现示例:
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)) )
数据帧是:
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
我正在尝试按行检查前两列中是否至少有一个值高于第三列中的相应阈值 (假设如果两个值中的任何一个高于截止值,我想存储一个 1)。
在示例中,我希望找到的是:
higher_than_cutoff
0
1
0
1
0
我一直在尝试使用以下(错误的)代码及其一些变体,但没有取得多大成功:
higher_than_cutoff <- apply( dat[, c("a", "b")], 1, function(x) any(x > dat[, "high_cutoff"]) )
能否就如何进行提供一些建议? 非常感谢任何帮助
这是一个可能的矢量化解决方案(如果您只使用 TRUE/FALSE
就可以,您可以删除开头的 +
)
+(rowSums(dat[-3L] > dat[, 3L]) > 0)
## [1] 0 1 0 1 0
如果你坚持apply
,你可以这样做
apply(dat, 1, function(x) +(any(x[-3] > x[3])))
## [1] 0 1 0 1 0
可以通过
获得所需的输出higher_than_cutoff <- apply(dat,1,function(x) (max(x[1],x[2])>x[3])*1)
你可以试试
as.integer(do.call(pmax,dat[-3]) > dat[,3])
#[1] 0 1 0 1 0
或者
((max.col(dat))!=3)+0L
#[1] 0 1 0 1 0
也许我误解了你想要实现的目标,但无需使用 apply
即可获得所需的输出,我们只比较完整的列向量,不需要按行操作。
+(dat$a > dat$high_cutoff | dat$b > dat$high_cutoff)
# [1] 0 1 0 1 0