-1

I am new in R programming. I want to add two consecutive rows of the first column in a table. Here is the function I tried:

x <- airquality[ , 1]
fun <- function(x){
for (i in 1: length(x))
y <- sum(x[i,1], x[i+1, 1])
y
}

I am not getting any display.

Please let me know my mistakes. Thanks

Rath
  • 17
  • 8
  • I would try and step through your code before complicating things by wrapping it in a function. Hints: 1) look at `dim(x)` its NULL as it is a vector.BUT within your loop you index it as if it has rows and columns, so use `x[i]` etc. (or else use `x <- airquality[ , 1, drop=FALSE]` when creating it, to retain its dimension) 2) Yuo have not indexed the output vector `y` so it will only store the last value rather than all. Try `y[i]`. 3) Before the loop you need to specify `y` ... `y <- numeric(length(x))` 4) `x[i+1]` does not exist for `i=length(x)` – user20650 Dec 05 '15 at 23:53
  • 1
    A lot of calculation in R can be vectorised, so no need for loops. You can do this same calculation with `tail(x, -1) + head(x, -1)` – user20650 Dec 05 '15 at 23:53
  • The errors arise because x is no longer a matrix or data.frame and so using an indexing function with two values fails. Use `x[i]` and `x[i+1` or as mentioned learn to use R vectorized functions. – IRTFM Dec 06 '15 at 00:03

2 Answers2

1

A few things I noticed:

  1. Make sure you run the function (you've declared it here, but you haven't run it)
  2. You're saving over the variable y each time the loop runs. In this case, your output will be the sum of the last two rows (I don't think this is what you want).
  3. x is a vector, not a dataframe, as you've selected only the first column. As such, x[i,1] will produce an error, because x is one-dimensional. x[i] is what you want.

Here's how you can do it:

x <- airquality[ , 1]

# Declare your function
fun <- function(x){
    y <- numeric()
    for (i in 1:(length(x)-1)){
        y <- c(y, sum(x[i], x[i+1])) # Add to y with each loop cycle
    }
    y
}

# Run your function:
fun(x)

Note: there are more efficient ways to do this in R, but it looks like you might be more comfortable with C++ style looping. But done is better than perfect, I guess.

edit: formatting

ojdajuiceman
  • 361
  • 2
  • 9
  • Thanks for your reply. Unfortunately, it's not working. I tried rollapply and it's working perfectly fine with that but I want to use my own function. I guess the problem is that the airquality dataset is data frame and I think that is creating problem. – Rath Dec 07 '15 at 04:11
1

I think this does what you need:

x + c(x[-1], 0)

x[-1] is x without the first element. The 0 on the end makes the two vectors the same length so they can be added.

Dan Lewer
  • 871
  • 5
  • 12