Writing R function with if enviornment

后端 未结 1 530
死守一世寂寞
死守一世寂寞 2020-12-12 05:09

I am trying to write a function which does different things, depending on the second argument. But I am getting an error all the time. Depending on the dimension of the matr

相关标签:
1条回答
  • 2020-12-12 06:14

    hnrstr<-1 is assigning the value of 1 to hnrstr. You do not want this in an if statement. You either meant "test that hnrstr is less than minus one", in which case add some whitespace. hnrstr < -1, or you meant "test that hnrstr is equal to one", in which case use double equals, hnsstr == 1.


    If X1, X2 and X3 are vectors, then x will be a matrix. That is, it has two dimensions. that means that later, after you've assigned y <- x (why do you need to do this?) y[ ,"X2","X3"]) doesn't make much sense because it implies that there are 3 dimensions, not two. This is what is causing the error. Did you mean y[, c("X2","X3")])?


    gsub accepts a vector, so after you've changed the previous code, you also need to change the call to that function. Do you want to pass it the second column or the third column or both (one after the other)?


    Those second if blocks look pointless. Have a think about how you can remove them.

    if (hnrstr<-1){
    x<-y
    }
    if (hnrstr<-2){
    x<-P  
    }
    

    You don't need a return statement at the end of the function. R automatically returns the last value that was calculated in the function.


    As Colin said, don't try and call your function "function". That's just asking for trouble. Change the line

    function <- function(x,hnrstr){
    
    0 讨论(0)
提交回复
热议问题