Skip to content

Dataframes: conditional calculations per row .

3 messages · Jesús Guillermo Andrade, jim holtman, David Winsemius

#
You can use 'ifelse':
+            ifelse(x$id == 2, 221,
+               ifelse(x$id == 3, 2221, 22221)))
id   cal
1   4 22221
2   1    21
3   3  2221
4   1    21
5   2   221
6   2   221
7   1    21
8   2   221
9   4 22221
10  2   221
11  2   221
12  3  2221
13  2   221
14  1    21
15  4 22221
16  3  2221
17  4 22221
18  1    21
19  3  2221
20  2   221


On Mon, Feb 9, 2009 at 5:11 PM, Jes?s Guillermo Andrade
<jgandradev at mac.com> wrote:

  
    
#
One way. there may be better. The apply function will work with just  
one row (or one column) at a time.

 > DF
    Month Week Estpassage MedFL
1   July   27        665    34
2   July   28       2232    35
3   July   29       9241    35
4   July   30      28464    35
5    Aug   31      41049    35
6    Aug   32      82216    35
7    Aug   33     230411    35
8    Aug   34     358541    35
9   Sept   35     747839    35
10  Sept   36     459682    36
11  Sept   37     609567    36
12  Sept   38     979475    36
13  Sept   39     837189    36

Build a function, say we call it switch.cond:

  switch.cond <- function (x) {
                if (x["Week"] >= 33) return( fun1(x) )  else  
return( fun2(x) ) }

  # Build two more functions to handle the dispatched rows

  fun1 <-function(x){ cat("do function 1\n") }
# replace the cat-call with your first calculation

  fun2 <-function(x){ cat("do function 2\n") }
# and use various x["<colname>"]'s as arguments

 > apply(DF, 1, switch.cond)
do function 2
do function 2
do function 2
do function 2
do function 2
do function 2
do function 1
do function 1
do function 1
do function 1
do function 1
do function 1
do function 1
NULL

HTH:
David Winsemius
On Feb 9, 2009, at 5:11 PM, Jes?s Guillermo Andrade wrote: