insert                package:R.utils                R Documentation

_I_n_s_e_r_t _v_a_l_u_e_s _t_o _a _v_e_c_t_o_r _a_t _c_e_r_t_a_i_n _p_o_s_i_t_i_o_n_s

_D_e_s_c_r_i_p_t_i_o_n:

     Insert values to a vector at certain positions.

_U_s_a_g_e:

     ## Default S3 method:
     insert(x, ats, values=NA, ...)

_A_r_g_u_m_e_n_t_s:

       x: The 'vector' of data values.

     ats: The indices of 'x' where the values should be inserted.

  values: A 'list' or a 'vector' of the values to be inserted.

     ...: Not used.

_A_u_t_h_o_r(_s):

     Henrik Bengtsson (<URL: http://www.braju.com/R/>)

_E_x_a_m_p_l_e_s:

     # Insert at first position
     x <- insert(1:3, ats=1, values=rep(NA,2))
     Ex <- c(NA,NA,1:3)
     print(x)
     stopifnot(identical(as.double(x),as.double(Ex)))

     # Insert at last position
     x <- insert(1:3, ats=4, values=2:1)
     Ex <- c(1:3,2:1)
     print(x)
     stopifnot(identical(as.double(x),as.double(Ex)))

     # Insert in the middle of a vector
     x <- insert(c(1,3,2,1), ats=2, values=2)
     print(x)
     stopifnot(identical(as.double(x),as.double(Ex)))

     # Insert multiple vectors at multiple indices at once
     x0 <- c(1:4, 8:11, 13:15)

     x <- insert(x0, at=c(5,9), values=list(5:7,12))
     print(x)
     Ex <- 1:max(x)
     stopifnot(identical(as.double(x),as.double(Ex)))

     x <- insert(x0, at=c(5,9,12), values=list(5:7,12,16:18))
     print(x)
     Ex <- 1:max(x)
     stopifnot(identical(as.double(x),as.double(Ex)))

     # Insert missing indices
     Ex <- 1:20
     missing <- setdiff(Ex, x0)
     x <- x0
     for (m in missing)
       x <- insert(x, ats=m, values=m)
     print(x)
     stopifnot(identical(as.double(x),as.double(Ex)))

