Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

r - Repeat vector when its length is not a multiple of desired total length

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the length.out argument of rep().

Here is an example using the built-in dataset cars.

str(cars)
'data.frame':   50 obs. of  2 variables:
 $ speed: num  4 4 7 7 8 9 10 10 10 11 ...
 $ dist : num  2 10 4 22 16 10 18 26 34 17 ...

Add grouping column:

cars$group <- rep(1:3, length.out=50)

Inspect the result:

head(cars)
  speed dist group
1     4    2     1
2     4   10     2
3     7    4     3
4     7   22     1
5     8   16     2
6     9   10     3

tail(cars)
   speed dist group
45    23   54     3
46    24   70     1
47    24   92     2
48    24   93     3
49    24  120     1
50    25   85     2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...