Alex
Alex

Reputation: 2788

Multiple one column by many others with data table

I have a large dataframe which is taking me away from my comfort tidyverse tools. I have one column in my data frame that I need to multiply the others by. How would I do this with data.table?

For example I have the following toy data:

multiplier a1  a2  
1          1   2    
2          1   2    
3          1   2   

And the desired result

   multiplier a1  a2  
    1          1   2    
    2          2   4    
    3          3   6   

I dplyr I would gather the as then multiply, then finally spread, but I am getting memory issues. How would I multiply the muliplier column by each row in data.table

Upvotes: 0

Views: 56

Answers (2)

Kill3rbee Lee Mtoti
Kill3rbee Lee Mtoti

Reputation: 246

Based on David Arenburg base R can be very fast. Using his example above, you get the same output without installing any libraries:

multiplier = 1:3 
a1 = c(1, 1, 1)
a2 = c(2, 2, 2)
data <- data.frame(multiplier,a1,a2)

data1<-data

Option 1

data[,2:3] <- data[,2:3] * data[, 1]

Option 2

data1[,2:nrow(data1)] <- data1[,2:nrow(data1)] * data1[, 1]

Output:

data
data1

  multiplier a1 a2
1          1  1  2
2          2  2  4
3          3  3  6

Upvotes: 1

kath
kath

Reputation: 7734

You can do this without spreading the data:

my_data %>% 
  mutate_at(c("a1", "a2"), funs(. * multiplier))

# A tibble: 3 x 3
#   multiplier    a1    a2
#        <int> <int> <int>
# 1          1     1     2
# 2          2     2     4
# 3          3     3     6

Data

my_data <- tibble(multiplier = 1:3, 
                  a1 = c(1L, 1L, 1L), 
                  a2 = c(2L, 2L, 2L))

Upvotes: 1

Related Questions