1

I'm stuck on what seems simple, but can't find a solution while searching.

I want to be able to repeat the following vector down the dataframe, for each Diamond_ID.

I have:

DIAMOND_ID <- c(1,2,3,4,5)
MY_MONTHS <- c(201501,201502,201503,201504,201505,201506)

So then for each Diamond ID, the months vector would repeat, i.e. the ideal solution would be a dataframe such as:

enter image description here

I imagine this is a loop function? This is my first week in R.

Thanks in advance.

thelatemail
  • 91,185
  • 12
  • 128
  • 188
  • 1
    `expand.grid(DIAMOND_ID, MY_MONTHS)` basically - I'm sure this is a duplicate though. – thelatemail Jul 12 '16 at 05:33
  • Maybe - http://stackoverflow.com/questions/26768819/combination-from-different-vectors or http://stackoverflow.com/questions/35346818/r-loop-for-repeat-a-vector-n-time ? – thelatemail Jul 12 '16 at 05:35

1 Answers1

0

See if that helps .

DIAMOND_ID <- c(1,2,3,4,5)
MY_MONTHS <- c(201501,201502,201503,201504,201505,201506)
DIAMOND_ID <- as.data.frame(DIAMOND_ID)
MY_MONTHS <- as.data.frame(MY_MONTHS)
df1 <- data.frame()
k <- 1
for (i in 1:nrow(DIAMOND_ID)) {
for (j in 1:nrow(MY_MONTHS)) {
df1[k,1] <- DIAMOND_ID[i,1] 
df1[k,2]  <- MY_MONTHS[j,1]  
k <- k+1
}  
}

colnames(df1)[1:2] <- c("Diamond ID","My Months")

Results :

> df1
   Diamond ID My Months
1           1    201501
2           1    201502
3           1    201503
4           1    201504
5           1    201505
6           1    201506
7           2    201501
8           2    201502
9           2    201503
10          2    201504
11          2    201505
12          2    201506
13          3    201501
14          3    201502
15          3    201503
16          3    201504
17          3    201505
18          3    201506
19          4    201501
20          4    201502
21          4    201503
22          4    201504
23          4    201505
24          4    201506
25          5    201501
26          5    201502
27          5    201503
28          5    201504
29          5    201505
30          5    201506
Pankaj Kaundal
  • 1,012
  • 3
  • 13
  • 25