r divide a row by another row if the next column matches in r

To divide one row of a data frame by another row if the next column matches in R, you can use the dplyr package from the tidyverse suite. Here is an example of how you can divide rows in a data frame by the rows matching the next column:

main.r
library(dplyr)

# Create a sample data frame
df <- data.frame(Group = c(1, 1, 2, 2),
                 Value1 = c(10, 20, 30, 40),
                 Value2 = c(5, 10, 15, 20))

# Divide one row by another row if the next column matches
df_new <- df %>%
  group_by(Group) %>%
  summarise(Value1 = Value1[Value2 == max(Value2)]/Value1[Value2 == min(Value2)],
            Value2 = max(Value2)) %>%
  ungroup()
405 chars
14 lines

In this example, we first group the data frame by the Group column. Then, we calculate the ratio of the Value1 column of rows where Value2 is the maximum and minimum within each group. Finally, we ungroup the data frame to get the final result.

gistlibby LogSnag