1 | initial version |
You can use the mutate
function from dplyr
along with the group_by
function to create a new column that performs division of a value with the initial group of values. Here's an example:
library(dplyr)
# create a dataframe with groups and values
df <- data.frame(
group = rep(c("A", "B"), each = 4),
value = c(10, 20, 30, 40, 5, 10, 15, 20)
)
# calculate the initial values for each group
initial_values <- df %>%
group_by(group) %>%
slice(1) %>%
rename(initial_value = value)
# join the initial values to the original dataframe
df <- df %>%
left_join(initial_values, by = "group")
# create a new column that performs division
df <- df %>%
mutate(new_column = value / initial_value)
# view the updated dataframe
df
In this example, we first create a dataframe with two groups and eight values. We then calculate the initial value for each group using group_by
and slice
. Next, we join the initial values to the original dataframe using left_join
. Finally, we create a new column new_column
using mutate
that divides the value
by the corresponding initial_value
.