0

there are a many similar questions to this question (how to repeat rows in a data.frame). I can´t implement the solutions to my problem. I think the difference is that I want to repeat every row of df1 as often as there are roes in df2.

df2 <- data.frame(col1=c('value1','value2','value3','value4','value5'),
col2=c('ani1','ani2','ani3','ani4','ani5'),co3=c('gut1','gut2','gut3','gut4','gut5'))
> df2
    col1 col2  co3
1 value1 ani1 gut1
2 value2 ani2 gut2
3 value3 ani3 gut3
4 value4 ani4 gut4
5 value5 ani5 gut5

df1 <- df2   ##as you can see, df1 and df2 are equal initially

##I have tried the following

select <- NULL
for(i in 1:nrow(df1)){
  k <- df1[rep(i),nrow(df2)]
  select <- rbind(select,k)
}

df1 %>%
  do( data.frame(column = rep(., each = nrow(df2)), stringsAsFactors = FALSE) )

select <- df1[rep(df1, nrow(df2))]

df1 <- df1[rep(df1[ ,1:3]),nrow(df2)]

##I want this result
df1
col1 col2  co3
1 value1 ani1 gut1
2 value1 ani1 gut1
3 value1 ani1 gut1
4 value1 ani1 gut1
5 value1 ani1 gut1
6 value2 ani2 gut2
7 value2 ani2 gut2
8 value2 ani2 gut2
9 value2 ani2 gut2
10 value2 ani2 gut2
11 value3 ani3 gut3
12 value3 ani3 gut3
13 value3 ani3 gut3
14 value3 ani3 gut3
15 value3 ani3 gut3
16 value4 ani4 gut4
17 value4 ani4 gut4
18 value4 ani4 gut4
19 value4 ani4 gut4
20 value4 ani4 gut4
21 value5 ani5 gut5
22 value5 ani5 gut5
23 value5 ani5 gut5
24 value5 ani5 gut5
25 value5 ani5 gut5

Every row is multiplied by the number of rows in df2. Thank you for any help

takeITeasy
  • 350
  • 3
  • 19

2 Answers2

0

You can repeat the row index :

df1[rep(1:nrow(df1), nrow(df1)), ]

Or using tidyr::uncount

library(dplyr)
tidyr::uncount(df1, n())
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

Also with tidyr :

library(tidyr)
complete(df1, co3, nesting(col1, col2))
py_b
  • 189
  • 6