The R Project SVN R

Rev

Rev 71749 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 71749 Rev 72563
Line 1... Line 1...
1
% File src/library/base/man/ifelse.Rd
1
% File src/library/base/man/ifelse.Rd
2
% Part of the R package, https://www.R-project.org
2
% Part of the R package, https://www.R-project.org
3
% Copyright 1995-2015 R Core Team
3
% Copyright 1995-2016 R Core Team
4
% Distributed under GPL 2 or later
4
% Distributed under GPL 2 or later
5
 
5
 
6
\name{ifelse}
6
\name{ifelse}
7
\title{Conditional Element Selection}
7
\title{Conditional Element Selection}
8
\usage{
8
\usage{
Line 81... Line 81...
81
## has many "yyyy-mm-29", but a few "yyyy-03-01" in the non-leap years
81
## has many "yyyy-mm-29", but a few "yyyy-03-01" in the non-leap years
82
y <- ifelse(as.POSIXlt(x)$mday == 29, x, NA)
82
y <- ifelse(as.POSIXlt(x)$mday == 29, x, NA)
83
head(y) # not what you expected ... ==> need restore the class attribute:
83
head(y) # not what you expected ... ==> need restore the class attribute:
84
class(y) <- class(x)
84
class(y) <- class(x)
85
y
85
y
86
## ==> Again a case where it is better *not* to use ifelse(), but
86
## This is a (not atypical) case where it is better *not* to use ifelse(),
87
## both more efficient and clear:
87
## but rather the more efficient and still clear:
88
y2 <- x
88
y2 <- x
89
y2[as.POSIXlt(x)$mday != 29] <- NA
89
y2[as.POSIXlt(x)$mday != 29] <- NA
-
 
90
## which gives the same as ifelse()+class() hack:
90
stopifnot(identical(y2, y))
91
stopifnot(identical(y2, y))
91
 
92
 
92
 
93
 
93
## example of different return modes:
94
## example of different return modes (and 'test' alone determining length):
94
yes <- 1:3
95
yes <- 1:3
95
no <- pi^(0:3)
96
no  <- pi^(1:4)
96
typeof(ifelse(NA,    yes, no)) # logical
97
utils::str( ifelse(NA,    yes, no) ) # logical, length 1
97
typeof(ifelse(TRUE,  yes, no)) # integer
98
utils::str( ifelse(TRUE,  yes, no) ) # integer, length 1
98
typeof(ifelse(FALSE, yes, no)) # double
99
utils::str( ifelse(FALSE, yes, no) ) # double,  length 1
99
}
100
}
100
\keyword{logic}
101
\keyword{logic}
101
\keyword{programming}
102
\keyword{programming}