R:如何在下面的代码中使用apply函数而不是循环

时间:2016-06-21 09:25:25

标签: r apply

我需要在代码中使用任何apply函数而不是for循环。下面提到的是示例代码和函数。

这是我的数据

  testdata<-data.table(x1=sample(1000),y1=sample(1000),x2=sample(1000),y2=sample(1000),h=sample(1000))

这是我的功能

testfunction<-function(x0,y0,x1,y1,x2,y2,h){
  x<-x0+x1+x2+y0+y1+y2
  y<-x+x0+y0
  d<-x+y
  R<-x+y+d
  result <- data.frame(d,R,x,y)
  return (result)
}

我当前使用for循环的代码是

resultdf<-data.frame(d=NA,R=NA,x=NA,y=NA)
for (i in 1:nrow(reqdata.LN)){
    resultdf[i,]<-testfunction(x0=1.2,y0=2.1,testdata$x1[i],testdata$x2[i],
                               testdata$y1[i],testdata$y2[i],testdata$h[i])
} 

我尝试过使用lapply和sapply,但错误很少

bb<-lapply(1:nrow(testdata),testfunction,x0=1.2,y0=2.1,testdata$x1[i],testdata$x2[i],
           testdata$y1[i],testdata$y2[i],testdata$h[i]) 

有些人可以告诉我们如何使用这个应用函数。

1 个答案:

答案 0 :(得分:5)

由于我们有data.table,因此可以直接应用该函数,因为+已经过矢量化。

res <- testdata[, testfunction(x0=1.2, y0=2.1, x1, y1, x2, y2, h)]
head(res)
#      d      R      x      y
#1 3923.9 7847.8 1960.3 1963.6
#2 2689.9 5379.8 1343.3 1346.6
#3 4523.9 9047.8 2260.3 2263.6
#4 3535.9 7071.8 1766.3 1769.6
#5 3183.9 6367.8 1590.3 1593.6
#6 3677.9 7355.8 1837.3 1840.6

注意:OP帖子中的函数返回data.frame。当我们使用data.table时,最好将其作为list返回,以便它将成为data.table对象

testfunction<-function(x0,y0,x1,y1,x2,y2,h){
   x<-x0+x1+x2+y0+y1+y2
   y<-x+x0+y0
   d<-x+y
   R<-x+y+d
   list(d= d,R=R,x= x,y = y)

 } 

head(testdata[, testfunction(x0=1.2, y0=2.1, x1, y1, x2, y2, h)])
#      d      R      x      y
#1: 3923.9 7847.8 1960.3 1963.6
#2: 2689.9 5379.8 1343.3 1346.6
#3: 4523.9 9047.8 2260.3 2263.6
#4: 3535.9 7071.8 1766.3 1769.6
#5: 3183.9 6367.8 1590.3 1593.6
#6: 3677.9 7355.8 1837.3 1840.6