Apply functions

Apply

# Apply function (paste pre) to every element of a list
lapply(c(1:22,'X','Y'), function(pre,post) paste(pre,post, sep =''), pre="chr")

# the same as lapply but output is vector of characters
sapply(c(1:22,'X','Y'), function(pre,post) paste(pre,post, sep =''), pre="chr")

# Get specific list elements from list with arrays
lapply(tt, `[`, i =c(1:3))

# Apply custom function to data set
findRegionIndex <-function (chromosome, position, regions){
  
  return (regions[chr == chromosome & start >= position & stop <= position])
}

apply(df.vaf,1,findRegionIndex, region=df.cov)

Lapply

# Apply function to vector resulting in lists with different length
freqs=list("999",  "99,9,0" , "99,93,0")
lapply(freqs, 'str_split', pattern = ',' )
out = sapply(freqs, 'str_split', pattern = ',' )
lapply(lapply(out, as.numeric), sum)

Map and mapply

Both map and mapply apply element-wise function to lists of parameters. Map is a wrapper for mapply which tries to simplify output

# Apply custom function with two parameters as input to every element of a vector
isCT <- function(x, y){
    return (x == "C" & y == 'T')
}
mapply(isCT,c("A","C"),c("T", "T"))

Do call

Do call calls a function with a certain name and feeds it with a


# Apply paste function row-wise to data.table columns
do.call(paste, dt[,2:9])
do.call(str_remove_all, list(string = dt$text, pattern = ' NA')