What are examples of when seq_along works, but seq produces unintended results?

前端 未结 2 1500
终归单人心
终归单人心 2020-12-12 12:56

What are good examples of when seq_along will work, but seq will produce unintended results?

From the documentation of ?seq we

2条回答
  •  抹茶落季
    2020-12-12 13:40

    If the input to seq is length 1 then the outputs between seq and seq_along will be different

    x <- 5
    for(i in seq(x)){
        print(x[i])
    }
    #[1] 5
    #[1] NA
    #[1] NA
    #[1] NA
    #[1] NA
    
    for(i in seq_along(x)){
        print(x[i])
    }
    #[1] 5
    

    We also see a difference if the input is a vector of Dates

    x <- Sys.Date() + 1:5
    seq(x)
    #Error in seq.Date(x) : 'from' must be of length 1
    seq_along(x)
    #[1] 1 2 3 4 5
    

提交回复
热议问题