2

I try to do a function which works with for loops with lapply instead. I am very new to R and not confortable with lapply. I especially don't get how to make an "if" condition.

My current code with for loops looks like that (it nomalizes volume series):

function(TableVolume,VolumeM,VolumeStD,n){
TableBN = TableVolume[n:nrow(TableVolume),]

for(k in 1:nrow(TableBN)){for (i in 2:ncol(TableBN)){if(!is.na(VolumeM[k,i]) && (VolumeM[k,i]) && (TableVolume[n-1+k,i]>VolumeM[k,i]+1.96/sqrt(n)*VolumeStD[k,i])){TableBN[k,i]=TableVolume[n-1+k,i]/VolumeM[k,i]}else{TableBN[k,i]=0}}}
TableBN=TableBN[n:nrow(TableVolume),]
return(TableBN)
}

I know from Apply over two data frames how to do a function that works with 2 data frame but I still don't see how to handle tests.

Thanks for your support, Vincent

Community
  • 1
  • 1
VincentH
  • 1,009
  • 4
  • 13
  • 24
  • found that: stat.ethz.ch/pipermail/r-help/2011-May/277193.html – VincentH Jun 26 '12 at 14:54
  • I am working on: binarisation=function(TableVolume,VolumeM,VolumeStD,n) {lapply(TableVolume,function(h){lapply(VolumeM,function(u){ lapply(VolumeStD,function(v,n){ f(h,u,v,n)=h/(u+1.96*v/sqrt(n)) }) }) }) } WorkingTable=binarisation(TableVolume,VolumeM,VolumeStD,n) remplissage=function(WorkingTable){lapply(WorkingTable,function(u){ function(u)=max(u-1,0) })} Which I try to have working – VincentH Jun 27 '12 at 08:49

1 Answers1

0

You need use lapply (or other apply family function). It is generally required when you have some non-vectorized function to apply to vectorized argument. Your function and conditions is a combinations of arithmetic functions, which are nicely vectorized. So you can use subsetting and ifelse function please see as below:

set.seed(123)

# simulation
TableBN <- matrix(1:12, nrow = 3)
VolumeM <- matrix(12:1, nrow = 3)
VolumeStD <- matrix(12:1, nrow = 3)
TableVolume <- matrix(abs(rnorm(10)), nrow = 5)


# function
f <- function(TableVolume, VolumeM, VolumeStD, n){
  TableBN <- TableVolume[n:nrow(TableVolume), ]

  ifelse(
    test = !is.na(VolumeM) && VolumeM && TableBN[, -1] > (VolumeM + 1.96 / sqrt(n) * VolumeStD), 
    yes = TableBN[, -1] / VolumeM,
    no = 0)
}

# Test
f(TableVolume, VolumeM, VolumeStD, 3)

Output:

0
Artem
  • 3,304
  • 3
  • 18
  • 41