Question

Here is a sample data and code I am trying to test:

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

I was wondering whether I really should use mapply in this case. Is there more efficient way to perform the operation?

Was it helpful?

Solution

Just use a vectorized solution

mydata[,1]*(mydata[,2]/mydata[,3])-mydata[,4]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top