Question

i'm developing a function to perform operations between two vectors (dataframes, for example), using the function "for":

> A <- c(1,2,3)
> B <- c(2)
> result <- c()
> for (i in 1:length(A))
+ {
+   for (j in 1:length(B))
+   {
+     result <- (A*B)
+   }
+ }
> result
[1] 2 4 6

However, when I increase the vector "B" to 2 values:

> A <- c(1,2,3)
> B <- c(2,4)

the function generates

Warning messages lost:
"Major object length is not a multiple of the length of a lower one."
> result
[1] 2 8 6

So, how i can create a loop that performs the operation against "A" for each row "B"?

Thnaks so much!

Was it helpful?

Solution

In your loop, you don't use the variables i and j but calculate the product A * B instead.

You can produce the desired result using sapply:

A=c(1,2,3); B=c(2,4)

sapply(A, "*", B)

#      [,1] [,2] [,3]
# [1,]    2    4    6
# [2,]    4    8   12

or matrix multiplication:

A %*% t(B)

#      [,1] [,2]
# [1,]    2    4
# [2,]    4    8
# [3,]    6   12

OTHER TIPS

As the error says, A's length has to be a multiple of B's one : if they have the same length, A*Bwill return a vector of same length whose terms will the multiplications of corresponding elements of A and B (A[1]*B[1],...A[n]*B[n]).

If length(A)=k*length(B), k>1, you will get a vector with same length as A with (A[1]*B[1]...A[l]*B[l],A[l+1]*B[1],A[l+2]*B[2]...A[kl]*B[l]), where l is B length and therefore kl is A length.

Here, 3 is a multiple of 1 but not of 2, hence the error you get.

In general, you can use outer:

outer(A, B, FUN='*')
#      [,1] [,2]
# [1,]    2    4
# [2,]    4    8
# [3,]    6   12
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top