Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have two variables, x (takes in 5 values) and y (takes in 11 values). When I want to run the argument,

> v <- 2*x +y +1

R responds:

Error at 2* x+y: Longer object length is not a multiple of shorter object length.

I tried: 1*x gives me 5 values of x, but y has 11 values. So R says it can’t add 11 to 5 values? – This raises the general question: Under what circumstances does recycling work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
616 views
Welcome To Ask or Share your Answers For Others

1 Answer

Recycling works in your example:

> x <- seq(5)
> y <- seq(11)
> x+y
 [1]  2  4  6  8 10  7  9 11 13 15 12
Warning message:
In x + y : longer object length is not a multiple of shorter object length
> v <- 2*x +y +1 
Warning message:
In 2 * x + y :
  longer object length is not a multiple of shorter object length
> v
 [1]  4  7 10 13 16  9 12 15 18 21 14

The "error" that you reported is in fact a "warning" which means that R is notifying you that it is recycling but recycles anyway. You may have options(warn=2) turned on, which converts warnings into error messages.

In general, avoid relying on recycling. If you get in the habit of ignoring the warnings, some day it will bite you and your code will fail in some very hard to diagnose way.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...