Ryan
Ryan

Reputation: 21

An If Statement inside an apply

I'm trying to use apply() to go through an array by rows, look at a column of 1's and 0's and then populate another column in that same array by using a function if the first column is a one, and a different function if it's a 0.

So it would be something like...

apply(OutComes, 1, if(risk = 1) {OutComes[, "Age"] = Function_1} else{OutComes[, "Age"] = Function_2} )

where OutComes is the array in question and risk is the variable which determines which function we use.

The aim is that 2 functions determine life length and people fall into one of the two categories, each with its own function. Based on the risk group, I want to use a different function to calculate the age, but this doesn't seem to be working.

Upvotes: 1

Views: 47

Answers (1)

Malaya
Malaya

Reputation: 311

apply() needs the name of a function; you need to define a function here, because no readymade function supplied.

example: apply(OutComes, 1, sum) -will return sums of each line. The number of output in vector is same as number or rows, so you can assign that to a variable and then add by cbind or replace the values of an existing column.

apply(OutComes, 1, function(x) { 
  if (x[n] == 1) {
    Function_1 ()
  }else {
    Function_2 ()
    } ) -> new_age
# x : is the working row at the time
# n : column number for "risk" # or # if(x["risk"] ==1)
# also note == instead of = at if 
OutComes = cbind(OutComes, new_age)
#or
OutComes$Age <- new_age

Upvotes: 1

Related Questions