Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding values in a row to the previous one in R

Tags:

r

row

I would like to perform a simple operation in R that is easily done in excel:

I have a col consisting of 5045 entries called K. I would like to create a second col L where the first value is L1=100+K[1] the second is L2=L1+K[2], the third is L3=L2+K[3] and so on.

Is there a simple way to do this in R? in Excel one just has to pull down the col.

like image 373
user1723765 Avatar asked Oct 24 '12 10:10

user1723765


People also ask

How do I add values to a row in R?

To add row to R Data Frame, append the list or vector representing the row, to the end of the data frame. nrow(df) returns the number of rows in data frame. nrow(df) + 1 means the next row after the end of data frame. Assign the new row to this row position in the data frame.

How do I get previous row values in R?

The previous record in R For the previous record, you have to remove the last entry of the column and add NA at the start of the column or other appropriate value. If you are dealing with subgroups in data like I do, check if the previous row contains the same category.

How do I sum two rows in R?

First of all, create a data frame. Then, using plus sign (+) to add two rows and store the addition in one of the rows. After that, remove the row that is not required by subsetting with single square brackets.

How do I add a row to an existing table in R?

You can quickly append one or more rows to a data frame in R by using one of the following methods: Method 1: Use rbind() to append data frames. Method 2: Use nrow() to append a row.


2 Answers

Try something like

L <- 100 + cumsum(K)
like image 189
George Dontas Avatar answered Oct 19 '22 19:10

George Dontas


One approach is to use cumsum() and cheat a little. For example, given K:

K <- 1:10

and to keep things simple I am adding 1 (not 100) to K[1], we want to produce:

> 1 + K[1]
[1] 2
> (1 + K[1]) + K[2]
[1] 4
> ((1 + K[1]) + K[2]) + K[3]
[1] 7
....

This is a cumulative sum. We need to cheat a little with the constant you want to add to the first element as we only want that to affect that first element, not be added to each element. Hence this is wrong

> L <- cumsum(1 + K) 
> L
 [1]  2  5  9 14 20 27 35 44 54 65

What we actually want is:

> L <- cumsum(c(1, K))[-1]
> L
 [1]  2  4  7 11 16 22 29 37 46 56

Wherein we concatenate the constant to the vector K as the first element and apply cumsum() to that, but drop the first element of the output from cumsum().

This can of course be done in a slightly simpler fashion:

> L <- 1 + cumsum(K)
> L
 [1]  2  4  7 11 16 22 29 37 46 56

i.e. compute the cumusum() and then add on the constant (which I now see is what @gd047 has suggested in their Answer.)

like image 4
Gavin Simpson Avatar answered Oct 19 '22 17:10

Gavin Simpson