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
.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-04-19 11:00:00 +0000
Seen: 14 times
Last updated: Sep 26 '22