avi
avi

Reputation: 105

rep() of rows from different dataframe

I have two data frames df1 and df2. Both df1 and df2 has 1051 rows and 30 columns. I want to perform like below

sapply(rep(df1[1,],df2[1,]),as.numeric)
sapply(rep(df1[2,],df2[2,]),as.numeric)
sapply(rep(df1[3,],df2[3,]),as.numeric) 

So the dimension of the resulting data frame will be 1051,30.

I was trying by the below code

fd<-data.frame()
for (i in 1:nrow(df1))
{
  for (j in 1:nrow(df2))
  {
    dfn<- sapply(rep(dfdia[i,],dfconc[j,]),as.numeric)
    fd<-rbind(fd,dfn)
    
  }
}

But this is incorrect I have understood because for this code for i=1 all j value will be taken then again for i=2 all j value will be taken. So How can I solve the problem? Thanks in advance.

foe example let
df1 is
1 1 2
2 5 3
df2 is
2 2 1
4 1 5

and result is expected as
1 1 1 1 2
2 2 2 2 5 3 3 3 3 3

Upvotes: 0

Views: 36

Answers (2)

akrun
akrun

Reputation: 887431

We could do this in a vectorized way with rep

g1 <- rowSums(df2)
split(rep(t(df1), t(df2)), rep(seq_along(g1), g1))
#$`1`
#[1] 1 1 1 1 2

#$`2`
#[1] 2 2 2 2 5 3 3 3 3 3

data

df1 <- structure(list(V1 = 1:2, V2 = c(1L, 5L), V3 = 2:3), 
       class = "data.frame", row.names = c(NA, -2L))
df2 <- structure(list(V1 = c(2L, 4L), V2 = 2:1, V3 = c(1L, 5L)), 
       class = "data.frame", row.names = c(NA, -2L))

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389095

You can split the data at each row and use rep in Map :

data <- Map(rep, asplit(df1, 1), asplit(df2, 1))
data

#[[1]]
#V1 V1 V2 V2 V3 
# 1  1  1  1  2 

#[[2]]
#V1 V1 V1 V1 V2 V3 V3 V3 V3 V3 
# 2  2  2  2  5  3  3  3  3  3 

data

df1 <- structure(list(V1 = 1:2, V2 = c(1L, 5L), V3 = 2:3), 
       class = "data.frame", row.names = c(NA, -2L))
df2 <- structure(list(V1 = c(2L, 4L), V2 = 2:1, V3 = c(1L, 5L)), 
       class = "data.frame", row.names = c(NA, -2L))

Upvotes: 1

Related Questions