Skip to content
Prev 342469 / 398498 Next

Creating Functions in R

Hi,


On Thu, Jul 24, 2014 at 9:35 AM, Pavneet Arora
<pavneet.arora at uk.rsagroup.com> wrote:
How about the introduction to R that comes with your installation?
It's got a section on writing
functions, and some other useful information that you seem to not have
learned yet.
Thank you for providing data with dput()!

There are a bunch of things wrong with your function, starting with
the lack of need for a function.

If I understand your description correctly, what you actually want is:

sub$deviation <- sub$value - 10

But for educational purposes, here goes:
this actually loops through the COLUMNS of data, so first you're subtracting
target from week, then from value
but coincidentally it gives you what you thought you were getting,
because you're overwriting deviation with each value of k, so the week
-target column is never saved. It's a really good idea to explicitly
mark the loop with { } too, to reduce confusion.
Hm. I don't know what you're trying to do with return() here, and
using both data.frame() and cbind() is superfluous. It isn't always
necessary, but I find it useful to explicitly name the columns of your
data frame when you create it, which gives

dev <- data.frame(data, deviation = deviation))
The last item of a function is what's returned, so all you really need here is

dev
dev only exists within the scope of the function. But you didn't
assign the return value of the function to anything. If you assign it
to an object named dev, then dev will exist in the global environment:

dev <- vmask(sub, 10)
You don't need a function. Just add the cumulative sum as a new column.

sub$Cusum <- cumsum(sub$deviation)


Sarah