Fernando Velasco Borea
Fernando Velasco Borea

Reputation: 183

Apply a variable operation, depending on groups using tidyverse [R]

I'm not quite sure even how to google my question, so I think an example is best to explain what I want to achieve. In summary, I'd like to multiply each value of a data frame, grouped by some variable, and the multiplication value will depend on which group is it. I'll place down an example:

    data <- data.frame(group = c("a", "b", "c"), value = c(1, 2, 3))
    multiplier <- c(a = 1, b = 2, c = 3)

    data %>% 
    group_by(group) %>%
    // Something that multiplies the value column by the corresponding multiplier contained in the vector

EDIT:

The expected returned values to replace the value column should be 1, 4, 9 respectively to the order.

Upvotes: 0

Views: 144

Answers (2)

Ian Campbell
Ian Campbell

Reputation: 24878

I think this should do it:

library(dplyr)
data %>%
    mutate(value = value * multiplier[as.character(group)])
#  group value
#1     a     1
#2     b     4
#3     c     9

Alternatively, you could append multiplier as a column of data and then calculate.

data %>%
    mutate(mutiplier = multiplier[as.character(group)]) %>%
    mutate(new.value = value * multiplier)
#  group value mutiplier new.value
#1     a     1         1         1
#2     b     2         2         4
#3     c     3         3         9

Upvotes: 1

akrun
akrun

Reputation: 887901

In base R, we can do

transform(merge(data, stack(multiplier), by.x = 'group', by.y = 'ind'),
        value = value * values)[-3]
#   group value
#1     a     1
#2     b     4
#3     c     9

Upvotes: 0

Related Questions