An efficient approach would be to shuffle a vector with the appropriate number of 1s and 0s for each column. You could define the following function to generate a matrix with a specified number of rows and the number of 1s in each column:
build.mat <- function(nrow, csums) {
sapply(csums, function(x) sample(rep(c(0, 1), c(nrow-x, x))))
}
set.seed(144)
build.mat(5, 0:5)
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] 0 0 0 0 1 1
# [2,] 0 0 0 1 0 1
# [3,] 0 0 0 0 1 1
# [4,] 0 1 1 1 1 1
# [5,] 0 0 1 1 1 1
To build a list, you might use lapply over the desired column sums for each matrix:
cslist <- list(1:3, c(4, 2))
set.seed(144)
lapply(cslist, build.mat, nrow=5)
# [[1]]
# [,1] [,2] [,3]
# [1,] 0 1 1
# [2,] 0 0 0
# [3,] 0 0 0
# [4,] 0 1 1
# [5,] 1 0 1
#
# [[2]]
# [,1] [,2]
# [1,] 0 0
# [2,] 1 0
# [3,] 1 1
# [4,] 1 0
# [5,] 1 1
forloop or runreplicateon it. You'll need to be much more specific, show what you've tried, and show sample input and desired output for this to be a good question.sample. For example, suppose, you want to create a vector of length 10 that sum to 5. i.e. 51s.v1 <- numeric(10); v1[sample(10, 5, replace=FALSE)] <- 1usingreplicateas @Gregor suggested, this can be looped. But, I am not sure whether the specified value is different for different columns. So, you may need to show some example to clear the confusion