lundi 7 septembre 2020

R apply function on DF rowwise if condition is met

Assume the following dataframe and functions:

cond    var_x    var_y
cond1       2        3
cond1       3        0.1
cond2       2        2
cond2       1        0.2
my_fun1 <- function(x) {
  act_vec <- rnorm(500, x, x/4)
  RT = 0
  for (i in 1:length(act_vec)) {
      my_act = act_vec[i]
      my_rt = my_act
      RT = RT + my_rt
  }
  RT = RT/500
  return(RT)
} 
my_fun2 <- function(x,y) {
  act_vec1 <- rnorm(500, x, x/4)
  act_vec2 <- rnorm(500, y, y/4)
  RT = 0
  for (i in 1:length(act_vec1)) {
      my_act1 = act_vec1[i]
      my_act2 = act_vec1[i]*act_vec2[i]
      my_rt = min(my_act1, my_act2)
      RT = RT + my_rt
  }
  RT = RT/500
  return(RT)
} 

The following code applies the function my_fun1 to every row in DF if DF$cond == 'cond1' and otherwise my_fun2.

my_test_vec = c()
for (i in (1:nrow(DF))) {
  if (DF$cond[i] == 'cond1') {
    my_test = my_fun1(DF$var_x[i])
  } else {
    my_test = my_fun2(DF$var_x[i], DF$var_y[i])
  }
  my_test_vec = c(my_test_vec, my_test)
}

This for-loop, however, is computational inefficient. Because of that, I would like to implement it in a way such that all the operations are applied in one go. My approach so far doesn't work and looks like this:

DF$results <- ifelse(DF$cond == 'cond1', 
                           my_fun1(DF$var_x), 
                           my_fun2(DF$var_x, DF$var_y))

Any suggestions?

Aucun commentaire:

Enregistrer un commentaire