rowsum                 package:base                 R Documentation

_G_i_v_e _R_o_w _S_u_m_s _o_f _a _M_a_t_r_i_x, _B_a_s_e_d _o_n _a _G_r_o_u_p_i_n_g _V_a_r_i_a_b_l_e

_D_e_s_c_r_i_p_t_i_o_n:

     Compute sums across rows of a matrix for each level of a grouping
     variable.

_U_s_a_g_e:

     rowsum(x, group, reorder = TRUE)

_A_r_g_u_m_e_n_t_s:

       x: a matrix or vector of numeric data.  Missing values are
          allowed.

   group: a vector giving the grouping, with one element per row of
          `x'.  Missing values are not allowed.

 reorder: if `TRUE', then the result will be in order of
          `sort(unique(group))', if `FALSE', it will be in the order
          that rows were encountered (and may run faster for large
          matrices). The default is to reorder the data, so as to agree
          with `tapply' (see example below).

_V_a_l_u_e:

     a matrix containing the sums.  There will be one row per unique
     value of `group'.

_A_u_t_h_o_r(_s):

     Terry Therneau

_S_e_e _A_l_s_o:

     `tapply'

_E_x_a_m_p_l_e_s:

     x <- matrix(runif(100), ncol=5)
     group <- sample(1:8, 20, T)
     xsum <- rowsum(x, group)

     ## same result another way, slower, and temp may be much larger than x
     temp <- model.matrix(~ a - 1, data.frame(a=as.factor(group)))
     xsum2<- t(temp) %*% x

     ## same as last one, but really slow
     xsum3 <- tapply(x, list(group[row(x)], col(x)), sum)

