DPatrick
DPatrick

Reputation: 431

R Studio: How to perform calculation for numbers from different rows indexes (tidyverse)

I have a dataframe that looks like this:

+-------+-------+
| value | index |
+-------+-------+
| 10    | 0.05  |
+-------+-------+
| 20    | 0.1   |
+-------+-------+
| 30    | 0.2   |
+-------+-------+
| 40    | 0.3   |
+-------+-------+
| 50    | 0.4   |
+-------+-------+
| 60    | 0.5   |
+-------+-------+

I would like to create a new column, where for each row i , it multiplies value (i-1) by index i. See table below for how this is calculated:

+-------+-------+-----------------+
| value | index | value_multipled |
+-------+-------+-----------------+
| 10    | 0.05  | = 0 * 0.05 = 0  |
+-------+-------+-----------------+
| 20    | 0.1   | = 10 * 0.1 = 1  |
+-------+-------+-----------------+
| 30    | 0.2   | = 20 * 0.2 = 4  |
+-------+-------+-----------------+
| 40    | 0.3   | = 30 * 0.3 = 9  |
+-------+-------+-----------------+
| 50    | 0.4   | = 40 * 0.4 = 16 |
+-------+-------+-----------------+
| 60    | 0.5   | = 50 * 0.5 = 25 |
+-------+-------+-----------------+

The final table would look like this:

+-------+-------+-----------------+
| value | index | value_multipled |
+-------+-------+-----------------+
| 10    | 0.05  | 0               |
+-------+-------+-----------------+
| 20    | 0.1   | 1               |
+-------+-------+-----------------+
| 30    | 0.2   | 4               |
+-------+-------+-----------------+
| 40    | 0.3   | 9               |
+-------+-------+-----------------+
| 50    | 0.4   | 16              |
+-------+-------+-----------------+
| 60    | 0.5   | 25              |
+-------+-------+-----------------+

Much appreciation for your help!

Upvotes: 2

Views: 110

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101247

A base R option using head

transform(
  df,
  value_multipled = index * c(0, head(value, -1))
)

gives

  value index value_multipled
1    10  0.05               0
2    20  0.10               1
3    30  0.20               4
4    40  0.30               9
5    50  0.40              16
6    60  0.50              25

Upvotes: 0

akrun
akrun

Reputation: 887048

We can use lag

library(dplyr)
df1 <- df1 %>%
   mutate(value_multiplied = lag(value, default = 0) * index)

-output

df1
#  value index value_multiplied
#1    10  0.05                0
#2    20  0.10                1
#3    30  0.20                4
#4    40  0.30                9
#5    50  0.40               16
#6    60  0.50               25

data

df1 <- data.frame(value = c(10, 20, 30, 40, 50, 60), 
      index = c(0.05, 0.1, 0.2, 0.3, 0.4, 0.5))

Upvotes: 3

Related Questions