Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R:如何使用谓词函数过滤矩阵?_R - Fatal编程技术网

R:如何使用谓词函数过滤矩阵?

R:如何使用谓词函数过滤矩阵?,r,R,作为R新手,我想用某些谓词函数过滤矩阵。 例如,我想过滤掉一行中所有相同的元素 所以我很高兴地编写了这样一个函数: af <- function(a){ n <- nrow(a) m <- ncol(a) a_Folger <- matrix(0, nrow=n, ncol=m) for(i in 1:n){ for(j in 2:m){ if( a[i,j] ==

作为R新手,我想用某些谓词函数过滤矩阵。 例如,我想过滤掉一行中所有相同的元素

所以我很高兴地编写了这样一个函数:

af <- function(a){
     n        <- nrow(a)
     m        <- ncol(a)
     a_Folger <- matrix(0, nrow=n, ncol=m)

     for(i in 1:n){
        for(j in 2:m){
           if( a[i,j] == a[i,j-1]) { 
              a_Folger[i,j]   <- a[i,j] 
              a_Folger[i,j-1] <- a[i,j]
           }
     }  
 }
 a_Folger
af你想要闻起来像“R”码的东西!!!。你确定???好啊
给你:

t(apply(a,1,function(x){ y<-rle(x); y[[2]][y[[1]]==1]<-0; rep(y[[2]],y[[1]]) }))

你能给我们举个例子,说明你的实际数据是什么样子的,以及你希望它是什么样子的吗?到目前为止,您只有一个0的矩阵,并且正在用0覆盖内容。查看实际数据并了解“过滤掉一行中所有相同的元素”的含义会很有帮助。谢谢您的指点。这一行看起来很有前途&这是我必须消化的东西。(B.T.我说“嗅觉”不是“臭”):“卡莱蒂泽,如果你觉得有用的话,请考虑选择这个答案:
> set.seed(1)
> a<-matrix(sample(1:10,100,replace=T),1000,1000)
> system.time(res1<-af(a))
   user  system elapsed
  4.680   0.000   4.683
> system.time(res2<-t(apply(a,1,function(x){ y<-rle(x); y[[2]][y[[1]]==1]<-0; rep(y[[2]],y[[1]]) })))
   user  system elapsed
  0.188   0.036   1.118
> all.equal(res1,res2)
[1] TRUE