if split data matrix rows according class labels in vector y
this, result 'names' this:
> x <- matrix(c(1,2,3,4,5,6,7,8),nrow=4,ncol=2) > y <- c(1,3,1,3) > x_split <- split(as.data.frame(x),y) $`1` v1 v2 1 1 5 3 3 7 $`3` v1 v2 2 2 6 4 4 8
i want loop through results , operations on each matrix, example sum elements or sum columns. how access each matrix in loop can that?
labels = names(x_split) (k in labels) { # how x_split[k] matrix? sum_class = sum(x_split[k]) # doesn't work }
in fact, don't want deal dataframes , named arrays @ all. there way can call split
without as.data.frame
, list of matrices or similar?
to split without converting data frame
x_split <- list(x[c(1, 3), ], x[c(2, 4), ])
more generally, write in terms of vector y
of length nrow(x)
, indicating group each row belongs, can write
x_split <- lapply(unique(y), function(i) x[y == i, ])
to sum results
x_sum <- lapply(x_split, sum) # [[1]] # [1] 16 # [[2]] # [1] 20
(or use sapply
if want result vector)
Comments
Post a Comment