Hands-On Geospatial Analysis with R and QGIS
上QQ阅读APP看书,第一时间看更新

Functions in R

We can also achieve the previous result by using a function. Let's name this function square:

square = function(data){
for(price in data){
print(price^2)
}
}

Now call the function as follows:

square(all_prices4$jan_price)

The following output also shows the squared price of jan_price:

Now suppose we want to have the ability to take elements to any power, not just square. We can attain it by making a little tweak to the function:

power_function = function(data, power){
for(price in data){
print(price^power)
}
}

Now suppose we want to take the power of 4 for the price in June, we can do the following:

power_function(all_prices4$june_price, 4)

We can see that the june_price column is taken to the fourth power as follows: