Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply each subsequent second column

Tags:

r

dplyr

I am trying to multiply the first columns with the first and with the third columns. Below you can see my data.

  df<-data.frame(  
  Stores=c(10,10,20,0,10),
  Value1=c(10,10,0,100,0),
  Value2=c(10,10,0,100,0),
  Value3=c(10,0,0,0,0),
  Value4=c(10,10,0,0,0)
  )

df

Now I want to multiply the first column Stores with each subsequent second column or in this case Value2 and Value4.

enter image description here

I tried to do this with mutate but I think that I am not in the right way because, in reality, I need to apply this on large data sets with around 50 columns.

df<-mutate(df,
           solved1=Stores*Value2)

So can anybody help me with how to solve this in an automatic way?

like image 831
silent_hunter Avatar asked Jan 25 '26 14:01

silent_hunter


2 Answers

Apart from akrun's pure tidyverse solution (which is preferable), we could use dplyover::over() for this kind of operations (disclaimer: I'm, the maintainer, and the package is not on CRAN).

We can create a sequence to loop over, below seq(2, 4, 2) running from 2 to 4 and then we can construct the variable names inside .(), below .("Value{.x}"), so in each iteration we loop over one of the values of our sequence (below: Value2 and Value4).

Finally, we need nice output names. Here we can set the .names argument to "solved{x_idx}" which says "take the string "solved" and append to it the index of the current iteration {x_idx}.

library(dplyr)
library(dplyover) # https://timteafan.github.io/dplyover/

df %>% 
  mutate(over(seq(2, 4, 2),
              ~ Stores * .("Value{.x}"),
              .names = "solved{x_idx}"
              )
         )
#>   Stores Value1 Value2 Value3 Value4 solved1 solved2
#> 1     10     10     10     10     10     100     100
#> 2     10     10     10      0     10     100     100
#> 3     20      0      0      0      0       0       0
#> 4      0    100    100      0      0       0       0
#> 5     10      0      0      0      0       0       0

Created on 2023-01-22 with reprex v2.0.2

like image 97
TimTeaFan Avatar answered Jan 27 '26 06:01

TimTeaFan


Base R solution, building on @onyambu’s comment:

new <- df[,1] * df[seq(3, ncol(df), by = 2)]
colnames(new) <- paste0("solved", seq_along(new))
df <- cbind(df, new)
df
  Stores Value1 Value2 Value3 Value4 solved1 solved2
1     10     10     10     10     10     100     100
2     10     10     10      0     10     100     100
3     20      0      0      0      0       0       0
4      0    100    100      0      0       0       0
5     10      0      0      0      0       0       0
like image 24
zephryl Avatar answered Jan 27 '26 08:01

zephryl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!