Home > Back-end >  Multiplying lines in R n times
Multiplying lines in R n times

Time:04-24

Is there a quick way of multiplying the number of lines in a dataframe n times?

n <- 1

steps <- range(0,n)
df1 <- data.frame(col1=c('A','B','C'))

such that the output is

enter image description here

CodePudding user response:

One way to do this would be with expand.grid.

steps <- range(0, 1)
col1 <- c('A','B','C')
expand.grid(col1 = col1, col2 = steps)

CodePudding user response:

You could use a tidyverse approach:

library(dplyr)
library(tidyr)

n <- 1

df1 %>% 
  uncount(n   1) %>% 
  group_by(col1) %>% 
  mutate(Col2 = row_number() - 1) %>% 
  ungroup()

This returns

# A tibble: 6 x 2
  col1   Col2
  <chr> <dbl>
1 A         0
2 A         1
3 B         0
4 B         1
5 C         0
6 C         1

CodePudding user response:

Here is a data.table way

setDT(df1)[rep(1:.N,each=n 1)][, col2:=rep(steps,length.out=.N)]
  •  Tags:  
  • r
  • Related