用环境写作R函数 [英] Writing R function with if enviornment
问题描述
我试图编写一个函数来完成不同的事情,具体取决于第二个参数。但是我总是遇到错误。根据矩阵的维数,函数应执行不同的任务。这里是一个例子
x <-cbind(X1,X2,X3)
函数<函数(x,hnrstr){
if(hnrstr <-1){
x <-data.frame(X1 = x [1],X2 = x [2],X3 = x [3] )$ x $ b y <,X2,X3] < - gsub({2,},,y [,X2,X3])
}
if(hnrstr <-2){
x <-data.frame(X1 = x [1],X2 = x [2])
如果(hnrstr <-1){
x <-y
}
if(hnrstr <-2){
(P <-x
) (x,c(3,3),函数(x,1))$ b(x,c(3,3))返回(x)
}
$ b
我得到这个错误:
drop&&& !has.j:'x&& amp;& amp;& y'
如果 如果块看起来毫无意义。 函数结尾不需要 正如Colin所说,不要试图打电话给你功能功能。这只是要求麻烦。更改行 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 I am getting the error:
If Those second if blocks look pointless. Have a think about how you can remove them.
You don't need a As Colin said, don't try and call your function "function". That's just asking for trouble. Change the line
这篇关于用环境写作R函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! hnrstr < - 1
将1的值赋给 hnrstr
。如果语句不符合中的要求,你的意思是测试hnrstr小于-1,在这种情况下添加一些空格。
hnrstr< -1
,或者你的意思是测试hnrstr等于1,在这种情况下,使用double等于, hnsstr == 1
p>
X1
, X2
和 X3
是向量,那么 x
将是一个矩阵。也就是说,它有两个维度。这意味着稍后在分配 y < - x
后(为什么需要这样做?) y [,X2 ,X3])
没有多大意义,因为它意味着有三个维度,而不是两个维度。这是导致错误的原因。您的意思是 y [,c(X2,X3)])
?
gsub
接受一个向量,因此在您更改之前的代码后,还需要将该调用更改为该函数。你想把它传递给第二列还是第三列或两者(一个接一个地)?
if(hnrstr <-1){
x <-y
if(hnrstr <-2){
x <-P
}
return
语句。 R自动返回函数中计算的最后一个值。
函数< - function(x,hnrstr){
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))
Error in drop && !has.j : invalid 'x' type in 'x && y'
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
.
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)?
if (hnrstr<-1){
x<-y
}
if (hnrstr<-2){
x<-P
}
return
statement at the end of the function. R automatically returns the last value that was calculated in the function.
function <- function(x,hnrstr){