I have a data frame with 1666 rows. I would like to add a column with a repeating sequence of 1:5
to use with cut()
to do cross validation. It would look like this:
Y x1 x2 Id1
1 .15 3.6 1
0 1.1 2.2 2
0 .05 3.3 3
0 .45 2.8 4
1 .85 3.1 5
1 1.01 2.9 1
... ... ... ...
I've tried the following 2 ways but get an error message as it seems to only add numbers in increments of the full seq()
argument:
> tr2$Id1 <- rep(seq(1,5,1), (nrow(tr2)/5))
Error in `$<-.data.frame`(`*tmp*`, "Id", value = c(1, 2, 3, 4, 5, 1, 2, :
replacement has 1665 rows, data has 1666
> tr2$Id1 <- rep(seq(1,5,1), (nrow(tr2)/5) + (nrow(tr2)%%5))
Error in `$<-.data.frame`(`*tmp*`, "Id", value = c(1, 2, 3, 4, 5, 1, 2, :
replacement has 1670 rows, data has 1666
Any suggestions?
Something, like this?
Use the
length.out
argument ofrep()
.Here is an example using the built-in dataset cars.
Add grouping column:
Inspect the result: