Some times, we need to merge multiple fastq files into one single fastq. However, for some reason, let us say there are multiple directories and within each directory, there are fastq files. These fastq files may or may not be equal in number and also may have different file naming pattern. Let us take a simple example where there are 3 samples and for each sample, there are uneven number of replicates to be merged. For the sake of simplicity, I took only one read file. 

Below is the organization of samples and their contents. Samples are located in a directory called "test".

Observe that each sample has uneven number of files and task is to merge fastq file sample wise and merged files will be placed in a directory by name "merged".  Following are the steps to do that:
  1. Create a dictionary with folder name as key and files as values (Key=value pair)
  2. Create a list of directories 
  3. Using lambda wild cards access each key and key values come from step 2.
Here is the snakemake code:
=====================================
# Import python library
import os

# Create an empty sample dictionary
sample_dict = {}

# Fill the dictionary. There are better ways of creating dictionary.
for i in (os.listdir("test")):
    sample_dict[i] = ["test" + os.sep + i + os.sep + j for j in os.listdir(os.path.join("test", i))]

# Print the dictionary to check if every thing is correct or not
print(sample_dict)

# Create sample list
samples = glob_wildcards("test/{sample}/{id}.fastq").sample
# Create unique sample list
samples = sorted(set(samples))
# Check the sample list
print(samples)

rule all:
    input:
        expand("merge/{sample}_merged.fastq", sample=samples)

rule first:
    input:
        lambda wildcards: sample_dict[wildcards.sample]
    output:
        "merge/{sample}_merged.fastq"
    shell:
        "cat {input} > {output}"
=====================================
lambda wildcards will access each element in the dictionary (sample_dict) based on the values in samples object. We have defined samples in rule all. Execute the code a directory upstream to the test.

Output would be stored in a folder called "merge".  Contents of merge directory, post merging is:

Now you see there are 3 merged files in merge directory. Now you can limit the files to R1 or R2 whichever you like.