under what circumstances does R recycle?

前端 未结 2 1584
忘了有多久
忘了有多久 2020-12-18 12:54

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:

2条回答
  •  半阙折子戏
    2020-12-18 13:41

    It doesn't work this way. You have to have vectors of the same length:

        x_samelen = c(1,2,3)
        y_samelen = c(10,20,30)
        x_samelen*y_samelen
        [1] 10 40 90
    

    If vectors are of the same length, the result is well defined and understood. You can do "recycling", but it really is not advisable to do so.

    I wrote a short script to make your two vectors of the same length, via padding the short vector. This will let you execute your code without warnings:

        x_orig <- c(1,2,3,4,5,6,7,8,9,10,11)
        y_orig <- c(21,22,23,24,25)
    
        if ( length(x_orig)>length(y_orig) ) {
            x <- x_orig
            y <- head(x = as.vector(t(rep(x=y_orig, times=ceiling(length(x_orig)/length(y_orig))))), n = length(x_orig) )   
            cat("padding y\r\n")
        } else {
            x <- head(x = as.vector(t(rep(x=x_orig, times=ceiling(length(y_orig)/length(x_orig))))), n = length(y_orig) )
            y <- y_orig
            cat("padding x\r\n")
        }
    

    The results are:

        x_orig
         [1]  1  2  3  4  5  6  7  8  9 10 11
        y_orig
        [1] 21 22 23 24 25
        x
         [1]  1  2  3  4  5  6  7  8  9 10 11
        y
         [1] 21 22 23 24 25 21 22 23 24 25 21
    

    If you reverse x_orig and y_orig:

        x_orig
        [1] 21 22 23 24 25
        y_orig
         [1]  1  2  3  4  5  6  7  8  9 10 11
        x
         [1] 21 22 23 24 25 21 22 23 24 25 21
        y
         [1]  1  2  3  4  5  6  7  8  9 10 11
    

提交回复
热议问题