R要替换的项目数不是替换长度/结果的倍数,但是是正确的 [英] R number of items to replace is not a multiple of replacement length / results however correct

查看:4128
本文介绍了R要替换的项目数不是替换长度/结果的倍数,但是是正确的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题上已经有了一些线索,但是经过这些,我还是无法弄清楚问题所在 - 请原谅我。



我试图运行代码

  for(i in 1:a){
matrix $ new_column [矩阵[i,1:b-1] ==矩阵$ col_b [i])
}

我正在尝试的是:
a 矩阵 找到包含与列 b 中的值相同的值的列(在每行的列中)。 总是有这样一个值),并将相应的列号写入* new_column *

My Code不断抛出错误


在矩阵$ new_column [i]中的警告< - 其中(矩阵[i,:要替换的
项的数目不是替换长度的倍数

然而,结果是完全正确的。已经尝试了


  • 首先创建* new_column *填充0
  • a a + 1 如上所述,结果是正确的,但是我觉得如果我做的一切都正确,我不应该得到警告信息,所以我非常感谢任何关于如何解决这个问题的建议。



    最后,不要问我为什么选择1:b-1,当我想从2跳到b-1时,我刚刚看到, 2:b-1,它会在第3列开始执行。

    解决方案

    / code>可以返回一个向量,如果有多个匹配的话。例如:

     哪((1:12)%% 2 == 0)#哪个都是偶数? 



    矩阵$ col_b [i] unique ?结果可能仍然是正确的。注意在这种情况下会发生什么:

      x < -  1:2 
    x [1] < - 3: 4
    x

    另外, 1:b-1 不会给你从 1 b - 1 的数字,但是从 1 b ,全部减去 1

      b < -  10 
    1:b-1

    你需要括号先强制减法: 1:(b-1)


    I know there have been already some threads on this, however going through those I was not able to figure out what the problem might be - please forgive me for that..

    I am trying to run the code

      for (i in 1:a){
        matrix$new_column[i]<-which(matrix[i,1:b-1]==matrix$col_b[i])
      }
    

    What I am attempting is: For the matrix of a lines and b columns, in each line´s columns 2 to b-1, find the one that contains the same value as the one in column b (there is always such a value) and write the according column number into the *new_column*

    My Code keeps throwing the error

    Warning in matrix$new_column[i] <- which(matrix[i, : number of items to replace is not a multiple of replacement length

    However, the result is completely correct. I have tried

    • creating the *new_column* filled with 0s first
    • changing the end indices from a to a-1 or a+1

    As said, the outcome is correct, however I feel I should not be getting the warning message if I did everything correctly, so I´m really grateful for any advice on how to fix this.

    Finally, don´t ask me why I chose 1:b-1 when I wanted to go from 2 to b-1, I just saw that when I would use 2:b-1, it would acutally begin in column 3..

    解决方案

    which() can return a vector if there are multiple matches. For example:

    which((1:12)%%2 == 0) # which are even?
    

    Is matrix$col_b[i] unique? The results may still look correct. Notice what happens in this case:

    x <- 1:2
    x[1] <- 3:4
    x
    

    Also, 1:b-1 does not give you the numbers from 1 to b - 1 but the number from 1 to b, all minus 1:

    b <- 10
    1:b-1
    

    You need parentheses to force the subtraction first: 1:(b - 1).

    这篇关于R要替换的项目数不是替换长度/结果的倍数,但是是正确的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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