Writing R function with if enviornment

a 夏天 提交于 2019-11-27 08:27:04

问题


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'

回答1:


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


来源:https://stackoverflow.com/questions/20067628/writing-r-function-with-if-enviornment

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!