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.
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.
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.
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.
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.
Try something like
L <- 100 + cumsum(K)
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With