R语言which函数详解以及Rcpp改写

4 篇文章 3 订阅

引言

首先来介绍一下R语言which函数的作用:which函数在向量、矩阵、数据框,列表、因子这些数据结构中有这重要的作用,可以查找特定的元素返回其在数据中的索引,因此非常方便操作数据。

which 函数的介绍

which函数中的参数:

function (x, arr.ind = FALSE, useNames = TRUE)

which函数的源码:

which <- function(x, arr.ind = FALSE, useNames = TRUE)
{
wh <- .Internal(which(x))
if (arr.ind && !is.null(d <- dim(x)))
arrayInd(wh, d, dimnames(x), useNames=useNames) else wh
}
arrayInd <- function(ind, .dim, .dimnames = NULL, useNames = FALSE) {
##-- return a matrix length(ind) x rank == length(ind) x length(.dim)
m <- length(ind)
rank <- length(.dim)
wh1 <- ind - 1L
ind <- 1L + wh1 %% .dim[1L]
dnms <- if(useNames) {
list(.dimnames[[1L]][ind],
if(any(nzchar(nd <- names(.dimnames)))) nd else
if(rank == 2L) c(“row”, “col”) # for matrices
else paste0(“dim”, seq_len(rank)))
}
ind <- matrix(ind, nrow = m, ncol = rank, dimnames = dnms)
if(rank >= 2L) {
denom <- 1L
for (i in 2L:rank) {
denom <- denom * .dim[i-1L]
nextd1 <- wh1 %/% denom # (next dim of elements) - 1
ind[,i] <- 1L + nextd1 %% .dim[i]
}
}
storage.mode(ind) <- “integer”
ind
}

供给想改进的同学学习!

which函数的一些小例子

1

x <- sample(1:10,25,T)

x的值: 10 9 3 10 9 9 10 10 3 10 7 9 9 7 2 4 2 8 8 5 4 7 3 8 4

which(x == 10)

10在向量x中的位置:1 4 7 8 10

给向量x命名,测试一下useNames = TRUE是否起作用!

names(x) <- letters[1:25]
which(x == 10,useNames = FALSE)
which(x == 10,useNames = TRUE)

在这里插入图片描述
然而并没有什么卵用!

2

a <- matrix(rep(1:3,times = c(3,3,3)),3,3)
which(a == 1,arr.ind = T)
which(a == 1,arr.ind = F)
which(a == 1,arr.ind = T,useNames = TRUE)
which(a == 1,arr.ind = F,useNames = FALSE)

结果:
在这里插入图片描述

which函数的改进以及时间对比

针对向量版本的我这里就不展示了!
根据矩阵中的某个元素返回其在矩阵中的位置!
Rcpp代码

sourceCpp(code = '
            #include <RcppArmadillo.h>
         //[[Rcpp::depends("RcppArmadillo")]]
         //[[Rcpp::export]]
       arma::mat whicha(arma::mat matrix,int what){
          arma::uvec out;//查找索引值
          out = find(matrix == what);//查找索引值(0开始)
          int n = matrix.n_rows; //行数
          int nl = out.n_elem; //查找元素总数
          
          arma::vec foo;
          arma::mat out1(nl,2);  //输出矩阵
          
       foo = arma::conv_to<arma::vec>::from(out); //查找值所在的向量索引
        out1.col(1) = floor(foo / n)+1;
        for(int i = 0;i < nl;i++){
            out1(i,0) = floor(out(i) % n)+1;}
        return out1;  }   ')

时间对比:

library(microbenchmark)

microbenchmark(which(z == 1,arr.ind = T),
               whicha(z,1) )

在这里插入图片描述

  • 9
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

麻利麻利哄吧

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值