I would like to call a function()
in R using variable names out of a string vector. In my specific case I used a for loop to generate numbered variable names. For example:
for (i in 1:3) {
assign(paste0("x",i),"value")
}
v <- paste0("x",c(1,2,3))
function(v) #Here I would like to call function with variables defined in for loop.
Background:
I have a data frame, which I filter by different criteria (controls, cases). The resulting vectors are turned into Grange objects and saved as variable or saved as a string vector of directories. Then I would like to call IDRfilterN3()
using the same number of Grange objects and paths. This function expects 3 Grange objects and 3 paths.
Here the specific example:
for (i in unique(samples$Treatment)){
ind <- samples$Treatment == i
for (j in samples$Replicate[ind]){
assign(paste0("peaks_",i,"_",j),toGRanges(file.path(samples$Peaks[ind][j]),format = "MACS2"))
assign(paste0("bam_",i,"_",j),file.path(samples$bamReads[ind][j]))
}
if(length(samples$Replicate[ind])==3) assign(paste0("peaks_",i,".idr"),IDRfilterN3(paste0("peaks_",i,"_",c(1,2,3)),paste0("bam_",i,"_",c(1,2,3))))
else print("Sample size not applicable. IDR failed!")
}
Here an example of a sample sheet and the steps I need to perform:
ids <- paste0("ID",c(1,2,3,4))
condition <- c(rep("A",2),rep("B",2))
replicate <- c(1,2,1,2)
pathA <- paste0("/dir/sample_",c(1,2,3,4))
pathB <- paste0("/dir/sample_",c(1,2,3,4),".bam")
d <- data.frame(ids,condition,replicate,pathA,pathB)
#Generate variable storing Grange object out of pathA path for each condition and replicate:
peakA1 <- toGRanges("/dir/sample_1")
peakA2 <- toGRanges("/dir/sample_2")
peakB1 <- toGRanges("/dir/sample_3")
peakB2 <- toGRanges("/dir/sample_4")
#Call IDR function for each condition (A, B) using the replicate variables and the path from column pathB
IDRfilterN3(peakA1, peakA2, "/dir/sample_1.bam", "/dir/sample_2.bam")
IDRfilterN3(peakB1, peakB2, "/dir/sample_3.bam", "/dir/sample_4.bam")
Thanks for your input.