loop to replicate a dataframe in R

Asked

Viewed 31 times

0

I have the following dataframe:

df <- data.frame(x1 = 1:7,x2 = 8:14, x3 = 15:21, x4 = 23:29, x5 = 30:36)

I need to replicate the value of each row 150, 100, 60, 43 times and for each column.

I tried to rep(df$x1, each=150), which replicates each line value 150 times but does not accept rep(df$x1, each=c(150,100,60,43))... I thought to make through a loop with for for the lines of each column.

for(i in 1:ncol(df)) {
    df$out[i] <- rep(df[,i])
    
   
     for(i in 1:nrow(df)) {
    df$out[i] <- rep(df[i,])
      
    }
    print(df$out)
}

However I’m not making any progress. Any suggestions?

  • 2

    You can provide an example of how you want the final result?

1 answer

0


Expected output is unclear,

  • may be the repeated basis times times, for each value in times;
  • can be each of the lines repeated times times, also for each value in times.

Here are two ways to do what is above.
First the data:

df <- data.frame(x1 = 1:7,x2 = 8:14, x3 = 15:21, x4 = 23:29, x5 = 30:36)
times <- c(150, 100, 60, 43)

The whole repeated base times times

i <- unlist(lapply(times, \(x) rep(seq_len(nrow(df)), times = x)))
df[i, ]

Each line repeated times times

j <- unlist(lapply(times, \(x) rep(seq_len(nrow(df)), each = x)))
df[j, ]
  • Sorry I didn’t make the exit clear, yet you answered me. Thank you very much! I wished the second option (j)!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.