R-循环并为每个行找到值 [英] R - loop and break after value found for each Rows

查看:55
本文介绍了R-循环并为每个行找到值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的矩阵是0-1.我想做的是进入这个矩阵并搜索1.每次找到1时,只需跳转或通过该行,以便每行仅记录1个值.

I have a matrix of 0-1. What I would like to do is to loop into this matrix and search for the 1. Each time a 1 has been found, to simply jump or pass that row, in order to only record 1 value per row.

我想知道序列的第一集是否为 1 .我在想

What I am trying to know if the first episode of the sequence is a 1. I was thinking there might be a solution with

break 

但是我不确定如何正确使用它.

But I am unsure how to use it properly.

这是我的第一个矩阵

SoloNight = structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 
1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 1, 0, 0), .Dim = 10:11)

这是我的空白矩阵-记录 1 .

This is my empty matrix - to record the 1.

matSolo = matrix(0, nrow = nrow(SoloNight), ncol = ncol(SoloNight) ) 

这是我尝试循环

for(i in 1:nrow(matSolo)){
  for(j in 1:ncol(matSolo)){
    if(SoloNight[i,j] == 1) break
    {matSolo [i,j] <- 1}
  }
}

在为每行找到值1之后如何 break ?

How can I break after finding the value 1 for each rows ?

任何建议我该怎么做?

(期望矩阵)

      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
 [1,]    0    0    0    0    0    0    0    0    0     0     0
 [2,]    0    0    0    0    0    0    0    0    0     0     0
 [3,]    0    0    0    0    0    0    0    0    0     0     0
 [4,]    0    0    0    0    0    0    0    0    0     0     0
 [5,]    0    0    0    0    0    0    0    0    0     0     0
 [6,]    0    0    0    0    0    0    0    0    0     0     0
 [7,]    0    0    0    0    0    0    0    0    0     0     0
 [8,]    0    0    0    1    0    0    0    0    0     0     0
 [9,]    0    1    0    0    0    0    0    0    0     0     0
[10,]    0    0    0    0    0    0    0    0    0     0     0

推荐答案

您似乎喜欢 for 循环,在这里看起来是自然的选择.只需将代码更改为此:

You seem to be fond of for loops and those seem like a natural choice here. Just change your code to this:

for(i in 1:nrow(matSolo)){
  for(j in 1:ncol(matSolo)){
    if(SoloNight[i,j] == 1) {
      matSolo [i,j] <- 1
      break
    }
  }
}

但是,对于大型矩阵,这将非常慢.幸运的是,它很容易翻译为Rcpp:

However, this will be quite slow for big matrices. Fortunately, it's easy to translate to Rcpp:

library(Rcpp)
cppFunction(
'IntegerMatrix firstOne(const IntegerMatrix mat) {
  IntegerMatrix res(mat.nrow(), mat.ncol());
  for (int i=0; i<mat.nrow(); i++) {
    for (int j=0; j<mat.ncol(); j++) {
      if (mat(i,j) == 1) {
        res(i,j) = 1;
        break;
      }
    }
  }
  return res;
}
')

firstOne(SoloNight)

这篇关于R-循环并为每个行找到值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆