# replacement error when feeding data from function into matrix in R [closed]

I am trying to write a function that creates simulated datasets.

The function takes the argument size, being the size of a group, and it is meant to produce a matrix with 100 columns with values 0 or 1, ranging from 1 to 100%, i.e, in the first column, 1% of "size" is "1" and 99% if "size" is "0" and in column ten, 10% of "size" is "1" and 90% if "size" is "0" and so on.

create.group <- function(size) {
group<-data.frame(matrix( nrow=size, ncol = 100))
for (i in 1:100) {
group[,i] <-sample(c(rep(1, (i*size/100)), rep(0, (size-(i*size/100)))))
}
group
}

create.group(100)


Now, the function does exactly what I want, as long as "size" is a multiple of 100, but any other number leads to an error, e.g. for size = 150

"*Error in [<-.data.frame(*tmp*, , i, value = c(0, 0, 0, 0, 0, 0, 0, : replacement has 149 rows, data has 150"

Sorry, probably a daft question, but if someone could give me a hint on where I went wrong, it would be appreciated, thanks!!

If the second argument of the rep function is not an integer, the function rounds it down and proceeds with the floor of the initial value. Consequently, for $$i=1$$, because the fraction $$\frac{i*size}{100}$$ is not an integer unless size is a multiple of $$100$$, one has less than one hundred entries to feed the first column of the matrix...

You may want to try this instead:

                       create.group <- function(size) {
group<-data.frame(matrix( nrow=size, ncol = 100))
for (i in 1:100) {
group[,i] <-sample(c(rep(1, floor((i*size/100))),
rep(0, ceiling((size-(i*size/100))))))
}
return(group)
}

• Great, that solved the problem. – siso777 Jun 1 at 13:45
• Thanks for explaining!!! – siso777 Jun 1 at 13:45
• You are most welcome. Best wishes! – Mickybo Yakari Jun 1 at 13:55