R中是否存在有效的替代方案?

时间:2013-10-03 14:39:32

标签: r mapply

以下是我要测试的示例数据和代码:

mydata<-structure(list(mpg = c(21, 21, 22.8, 21.4), cyl = c(6, 6, 4, 
6), disp = c(160, 160, 108, 258), hp = c(110, 110, 93, 110)), .Names = c("mpg", 
"cyl", "disp", "hp"), class = "data.frame", row.names = c("Mazda RX4", 
"Mazda RX4 Wag", "Datsun 710", "Hornet 4 Drive"))


 for(i in 1:4){
    show(mydata[i,1]*(mydata[i,2]/mydata[i,3])-mydata[i,4])
 }
[1] -109.2125
[1] -109.2125
[1] -92.15556
[1] -109.5023


 mapply(function(x,y,w,z){x*(y/w)-z},as.list(mydata[1]),as.list(mydata[2]),as.list(mydata[3]),as.list(mydata[4]))
            mpg
[1,] -109.21250
[2,] -109.21250
[3,]  -92.15556
[4,] -109.50233

我想知道在这种情况下我是否真的应该使用mapply。有更有效的方法来执行操作吗?

1 个答案:

答案 0 :(得分:6)

只需使用矢量化解决方案

mydata[,1]*(mydata[,2]/mydata[,3])-mydata[,4]