user2963882
user2963882

Reputation: 627

Writing R function with if enviornment

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 matrix, the function should perform different tasks. Here is an example

x<-cbind(X1,X2,X3)

function<-function(x,hnrstr){
  if (hnrstr<-1){ 
    x<-data.frame(X1=x[1],X2=x[2],X3=x[3])
    y<-x 
    y[ ,"X2","X3"]<- gsub(" {2, }"," ",y[ ,"X2","X3"])       
  }

  if (hnrstr<-2){ 
    x<-data.frame(X1=x[1],X2=x[2])
    P<-x 
  }  
  if (hnrstr<-1){
    x<-y
  }
  if (hnrstr<-2){
    x<-P  
  }
  return(x)
}

apply(x,c(3,3), function(x,1))

I am getting the error:

Error in drop && !has.j : invalid 'x' type in 'x && y'

Upvotes: 1

Views: 2245

Answers (1)

Richie Cotton
Richie Cotton

Reputation: 121077

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){

Upvotes: 2

Related Questions