Error when attempting to use "function()" to repeat code for different GAlignment objects

32 Views Asked by At

I would like to use "function()" or a for loop to make my code cleaner and less repetitive. I am currently just rewriting the same code 44 times.

I am only showing four of the 44 samples in the example code below:

tissue <- data.frame(tissue = c("oneleaf_1", "oneleaf_2","oneroot_1", "oneroot_2")) 

# 1Leaf1
uORFsCount1Leaf1=countOverlaps(uORFs,oneleaf_1_bam_f, minoverlap=18)
uORFsCount1Leaf1_df <- as.data.frame(uORFsCount1Leaf1)
uORFsCount1Leaf1_v <- uORFsCount1Leaf1_df[['uORFsCount1Leaf1']]
uCounts_1Leaf1 <-sum(uORFsCount1Leaf1_v, na.rm=TRUE)

uFrac_1Leaf1 = uCounts_1Leaf1/100

# 1Leaf2
uORFsCount1Leaf2=countOverlaps(uORFs,oneleaf_2_bam_f, minoverlap=18)
uORFsCount1Leaf2_df <- as.data.frame(uORFsCount1Leaf2)
uORFsCount1Leaf2_v <- uORFsCount1Leaf2_df[['uORFsCount1Leaf2']]
uCounts_1Leaf2 <-sum(uORFsCount1Leaf2_v, na.rm=TRUE)

uFrac_1Leaf2 = uCounts_1Leaf2/100

# 1Root1
uORFsCount1Root1=countOverlaps(uORFs,oneroot_1_bam_f, minoverlap=18)
uORFsCount1Root1_df <- as.data.frame(uORFsCount1Root1)
uORFsCount1Root1_v <- uORFsCount1Root1_df[['uORFsCount1Root1']]
uCounts_1Root1 <-sum(uORFsCount1Root1_v, na.rm=TRUE)

uFrac_1Root1 = uCounts_1Root1/100

# 1Root2
uORFsCount1Root2=countOverlaps(uORFs,oneroot_2_bam_f, minoverlap=18)
uORFsCount1Root2_df <- as.data.frame(uORFsCount1Root2)
uORFsCount1Root2_v <- uORFsCount1Root2_df[['uORFsCount1Root2']]
uCounts_1Root2 <-sum(uORFsCount1Root2_v, na.rm=TRUE)

uFrac_1Root2 = uCounts_1Root2/100

This is my attempt at using "function()":


tissue <- data.frame(tissue = c("oneleaf_1", "oneleaf_2","oneroot_1", "oneroot_2")) 

fract_calc <- function(tissue){
  uORFsCountTissue=countOverlaps(uORFs,paste0(tissue,"_bam_f"), minoverlap=18)
  uORFsCountTissue_df <- as.data.frame(uORFsCountTissue)
  uORFsCountTissue_v <- uORFsCountTissue_df[['uORFsCountTissue']]
  uCounts_Tissue <-sum(uORFsCountTissue_v, na.rm=TRUE)
 
  paste0("uFrac_",tissue,"") <- uCounts_Tissue/100
  
  return(uFrac_tissue)
}

This is the error I get when I run my code:

> fract_calc(one_leaf1)
Error in h(simpleError(msg, call)) :
error in evaluating the argument 'subject' in selecting a method for function 'countOverlaps': object 'one_leaf1' not found

Thank you for reading. I appreciate any help.

0

There are 0 best solutions below