Showing posts with label ifelse. Show all posts
Showing posts with label ifelse. Show all posts

Thursday, February 23, 2012

Ternary ifelse ( ?: ) in different languages


  • AWK
$ awk 'ORS=NR%3?",":"\n"' student-marks
  • Perl /PHP
$result = ($a > $b) ? $x : $y;

In Per6, use double ? and ! instead.
$result = ($a > $b) ?? $x !! $y;
  • R
ifelse(a>0,a,0)Ternary operator (if?true:false)
  • bash/linux
ternary operator ? : is just short form of if/else
case "$b" in
 5) a=$c ;;
 *) a=$d ;;
esac
Or
 [[ $b = 5 ]] && a="$c" || a="$d"

Reference:
http://en.wikipedia.org/wiki/Ternary_operation
http://en.wikipedia.org/wiki/%3F:

Friday, September 16, 2011

ifelse function in R only returns the first element

If you also favor to use the function, be aware of the returned value. For example:

> ifelse(1>0, 3, 4) 
[1] 3
> ifelse(1>0, c(2, 3), c(4, 5))   # only the first element returned.
[1] 2
 
> ifelse(c(1:10)>5, 'on', 'off')
 [1] "off" "off" "off" "off" "off" "on"  "on"  "on"  "on"  "on" 


Here is another nice example (from http://rwiki.sciviews.org/doku.php?id=tips:programming:ifelse)

> varD <- log(0:9)  # A vector like this one that contains -Inf could be troublesome in subsequent manipulations
> varD
 [1]      -Inf 0.0000000 0.6931472 1.0986123 1.3862944 1.6094379 1.7917595
 [8] 1.9459101 2.0794415 2.1972246
> varD <- ifelse(is.finite(varD), varD, NA)   # Remove the -Inf, replace with NA
> varD
 [1]        NA 0.0000000 0.6931472 1.0986123 1.3862944 1.6094379 1.7917595
 [8] 1.9459101 2.0794415 2.1972246