Tom*_*ans 7 r apply lapply sapply
我想运行一个查看两个向量的函数,根据两个向量中值的符号返回不同的值.我编写了一个函数来比较两个值,但后来我想在两个向量上运行它.所以我使用了sapply,但是我得到的结果与预期不同.
bear.correction<- function(x,y){
if(x > 0 && y < 0){
return(90)
}else if(x < 0 && y < 0){
return(180)
}else if(x < 0 && y > 0){
return(270)
}else return(0)
}
Run Code Online (Sandbox Code Playgroud)
以下给出了预期的(和期望的)结果:
bear.correction(1,-1)
bear.correction(1,1)
bear.correction(-1,1)
bear.correction(-1,-1)
Run Code Online (Sandbox Code Playgroud)
结果:90,0,270,180
然而,当我尝试进行相同的比较,但使用带有sapply的向量时,我得到了不同的结果:
x <- c(1,1,-1,-1)
y <- c(-1,1,1,-1)
sapply(x,bear.correction,y)
Run Code Online (Sandbox Code Playgroud)
结果:90,90,180,180.
我看不出有什么不对,所以请帮忙!
S. *_*ica 11
您应该使用mapply()而不是sapply():
mapply(bear.correction,x,y)
Run Code Online (Sandbox Code Playgroud)
为什么?您sapply()适用bear.correction()于...的每个条目,x但在每种情况下都将整个 y向量作为第二个参数给出,因此bear.correction()仅查看y所有四个案例中的第一个条目.要在多个向量(或其他数据结构)中"遍历"多个条目,请使用mapply().
你应该使用mapply而不是sapply
mapply(bear.correction,x,y)
[1] 90 0 270 180
Run Code Online (Sandbox Code Playgroud)