【问题标题】:Vectorizing a for loop of a logical comparison of vectors of different length in R向量化 R 中不同长度向量的逻辑比较的 for 循环
【发布时间】:2017-12-06 16:37:37
【问题描述】:

在R中,不同长度的向量无法进行有意义的比较,即

x = 1:10
y = 7:12
x >= y

给出y 比x 短的警告。我想对x 到y 的每个元素进行比较,并保存或转换结果向量,如下所示

v = numeric()
for(i in 1:length(x)){
  v[i] = sum( x[i] >= y )
}

这个操作很慢 - 有没有直接的方法可以到达这里?替代sum 考虑将i 保存在矩阵v[i,] 的行中。

【问题讨论】:

  • 试试colSums(sapply(x, '>=', y))或rowSums(outer(x, y, FUN= '>='))
  • @akrun 谢谢。

标签: r performance for-loop vector comparison


【解决方案1】:

我们可以通过outer 和rowSums 做到这一点

rowSums(outer(x, y, FUN= '>='))
#[1] 0 0 0 0 0 0 1 2 3 4

或者另一种选择是循环使用sapply,然后得到逻辑矩阵的colSums

colSums(sapply(x, '>=', y))
#[1] 0 0 0 0 0 0 1 2 3 4

我们也可以翻译Rcpp中的for循环

#include <Rcpp.h>

using namespace Rcpp;
using namespace std;

//[[Rcpp::export]]

NumericVector getSum(NumericVector v1, NumericVector v2) {
    NumericVector v(v1.size());

    for(int i = 0; i <= v1.size(); i++) {
        v[i] = sum(v1[i] >= v2 );


    }
    return(v);



}

-来自 R 控制台

library(Rcpp)
sourceCpp("rcppTrial.cpp")
getSum(x, y)
 #[1] 0 0 0 0 0 0 1 2 3 4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    相关资源
    最近更新 更多