虽然您可能无法完全避免迭代,因为您正在比较每个元素compare_comp
向量到完整向量Compound
每一个test_set
and train_set
,但是您可以使用更紧凑的分配apply家庭职能。
具体来说,sapply
返回布尔值的逻辑矩阵 (TRUE
, FALSE
)我们将其分配给初始化矩阵的相应位置,其中TRUE
转换为 1 和FALSE
to 0.
# SAPPLY AFTER MATRIX INITIALIZATION
compound_test2 <- matrix(0, nrow(test_set), length(compare_comp))
compound_train2 <- matrix(0, nrow(train_set), length(compare_comp))
compound_test2[] <- sapply(compare_comp, function(x) x == test_set$Compound)
compound_train2[] <- sapply(compare_comp, function(x) x == train_set$Compound)
或者,很少使用和已知的vapply
(如同sapply
但必须定义输出类型),返回等效矩阵,但作为数字类型。
# VAPPLY WITHOUT MATRIX INITIALIZATION
compound_test3 <- vapply(compare_comp, function(x) x == test_set$Compound,
numeric(length(compare_comp)))
compound_train3 <- vapply(compare_comp, function(x) x == train_set$Compound,
numeric(length(compare_comp)))
使用随机数据进行测试确认(请参阅下面的演示),两个版本都与您的循环版本相同
identical(compound_test1, compound_test2)
identical(compound_train1, compound_train2)
# [1] TRUE
# [1] TRUE
identical(compound_test1, compound_test3)
identical(compound_train1, compound_train3)
# [1] TRUE
# [1] TRUE
Online Demo https://rextester.com/FUMJ83898