Ask Your Question
3

How can I incorporate a new column in dplyr that performs division of a value with the initial group of values (similar to vlookup)?

asked 2021-04-19 11:00:00 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-09-26 00:00:00 +0000

ladyg gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2021-04-19 11:00:00 +0000

Seen: 14 times

Last updated: Sep 26 '22