Home > Back-end >  R coding - building a dynamic pattern
R coding - building a dynamic pattern

Time:06-04

i need to create a dynamic repeating well pattern column in R as part of a script to generate an input file for an automated pipetter. The goal is to make a dataframe column that repeats the pattern in wellVec1 a total of repeatValue times, followed by repeating wellVec2 a total of repeatValue times in the same column, and so on until all of the wellVec patterns have been used. It should look like this:

A1
C1
A1
C1
A2
C2
A2
C2
A3
C3
A3
C3

using these simplified examples of the wellVec patterns:

repeatValue <- 2
wellVec1 <- c("A1", "C1") 
wellVec2 <- c("A2", "C2")  
wellVec3 <- c("A3", "C3") 

Thanks for your help!

CodePudding user response:

Use rep() and combine elements whith c():

repeatValue <- 2
wellVec1 <- c("A1", "C1") 
wellVec2 <- c("A2", "C2")  
wellVec3 <- c("A3", "C3") 

out < - c(rep(wellVec1,repeatValue),rep(wellVec2,repeatValue),rep(wellVec3,repeatValue))

out:

> out
 [1] "A1" "C1" "A1" "C1" "A2" "C2" "A2" "C2" "A3" "C3" "A3" "C3"

CodePudding user response:

Here's an option using a function, where you only need to provide a repeated value and all of your data frames:

library(purrr)
library(dplyr)

repeatValue <- 2
wellVec1 <- c("A1", "C1") 
wellVec2 <- c("A2", "C2")  
wellVec3 <- c("A3", "C3") 

rep_func <- function(repeatValue, ...) {
  .dots <- list(...)
  purrr::map_df(.dots, ~rep(., repeatValue) %>%  as_tibble())
}

rep_func(2, wellVec1, wellVec2, wellVec3)


#> # A tibble: 12 × 1
#>    value
#>    <chr>
#>  1 A1   
#>  2 C1   
#>  3 A1   
#>  4 C1   
#>  5 A2   
#>  6 C2   
#>  7 A2   
#>  8 C2   
#>  9 A3   
#> 10 C3   
#> 11 A3   
#> 12 C3
  • Related