Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用if环境编写R函数_R_Function_Gsub - Fatal编程技术网

用if环境编写R函数

用if环境编写R函数,r,function,gsub,R,Function,Gsub,我试着写一个函数,根据第二个参数做不同的事情。但我一直在犯错误。根据矩阵的维数,函数应执行不同的任务。这里有一个例子 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

我试着写一个函数,根据第二个参数做不同的事情。但我一直在犯错误。根据矩阵的维数,函数应执行不同的任务。这里有一个例子

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

hnrstr你能在操作符周围添加一些空格吗,这样我们就可以知道你是否/何时使用了小于符号
我认为在你的if语句中,测试应该是例如if(hnrstr==2),而不是(hnrstrI)放在switch operator中。
switch(hnrstr,“1”={…},“2”={…})
的错误仍然相同(x,1,strassestand(x,“1”))
apply语句应该是
apply(x,1,strassestand,hnrstr=1)
问题是,如果我使用
x[,c(“X2”,“X3”)],我想用gesub删除字符串中的空格我想在数据帧的两个向量上都使用gsub。我需要X1将一些if命令放在一些gsub命令上。您可能还想提到:
function@user2963882您可以使用循环应用
gsub
(或者是
for
循环,或者使用
lappy
函数).在你这么做之前,我建议你先练习一下索引。
Error in drop && !has.j : invalid 'x' type in 'x && y'
if (hnrstr<-1){
x<-y
}
if (hnrstr<-2){
x<-P  
}
function <- function(x,hnrstr){