Michael
Michael

Reputation: 345

Using a For Loop to multiply variables by numbers in a matrix

This should be relatively simple but I am new to R and cannot quite figure this out.

I will illustrate what I am trying to do.

I have the following:

names <- c("A","B","C")
values <- c(3,6,9)
values2 <- c(5,10,15)
y <- c("2019")
r <- c("1")
t <- c("Team A", "Team B", "Team C")
mgn <- c(33, 56, 63)
df1 <- data.frame(names,y,r,t,values,values2,mgn)

I also have a matrix:

numbers <- matrix(1:6, nrow = 3, ncol = 2)

I am trying to loop through each of the values and values2 in my df1 and multiply these by the values in my numbers matrix like so:

3 x 1 = 3
5 x 4 = 20

6 x 2 = 12
10 x 5 = 50

9 x 3 = 27
15 x 6 = 90

I would then like to print each of these values like:

    values    values2
[1] 3          20
[2] 12         50
[3] 18         90 

I tried the following (just for the first values col):

for(col in 1:ncol(numbers)){ 
    df1$values %*% numbers[col]
    print(df1$values)
  }

But this is the ouput I get:

[1] 3 6 9
[1]  6 12 18
[1]  6 12 18
[1] 12 24 36
[1] 12 24 36
[1] 24 48 72

I then would like to repeat the process, so that the next row of values and values2 is multiplied by the first row again in numbers (2 and 5) so that:

3 x 2 = 6
5 x 5 = 25

and so on, until all the combinations are calculated.

This would give me the output like so:

3 x 1 = 3
5 x 4 = 20

6 x 1 = 6
10 x 4 = 40

9 x 1 = 9
15 x 4 = 60

Then it should go to the next line of values and values2 and repeat:

3 x 2 = 6
5 x 5 = 25

6 x 2 = 12
10 x 5 = 50

9 x 2 = 18
15 x 5 = 75

And finally the last line:

3 x 3 = 9
5 x 6 = 30

6 x 3 = 18
10 x 6 = 60

9 x 3 = 27
15 x 6 = 90

Finally, I would like to loop through each of these, add them together like:

sumvalues = values + values2

create a total column like:

df1%>%group_by(y, r, t)%>%dplyr::mutate(total=sum(sumvalues)

then obtain the pearson correlation for each by:

cor(mgn, sumvalues, method = "pearson")

So I can have the output like so:

     sumvalues    total    mgn    pearson
[1] 
[2]
[3] 

Upvotes: 0

Views: 406

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388862

Your first output can be reached by :

df1[-1] * numbers

#  values values2
#1      3      20
#2     12      50
#3     27      90

To get all possible combinations you can use apply with sweep :

apply(numbers, 1, function(x) sweep(df1[-1], 2, x, `*`))

#[[1]]
#  values values2
#1      3      20
#2      6      40
#3      9      60

#[[2]]
#  values values2
#1      6      25
#2     12      50
#3     18      75

#[[3]]
#  values values2
#1      9      30
#2     18      60
#3     27      90

Upvotes: 1

Ben
Ben

Reputation: 1144

Here's how I did it:

#### make the two objects to have the same dimensions:
df2<-df1[ ,c(2:3)]

#### multiply and create new object:
new<-df2*numbers

#### if you want to return the first column to df1:
df3<-cbind(df1[1],x)
print(df3)

Upvotes: 2

Related Questions