# Examples of the first kind of usage of the function
#
df <- data.frame(x = rnorm(n=20), y = rnorm(n=20))
df <- df[do.call(order,df),]
(df <- within(df,{
x1=cases(x>0,x<=0)
y1=cases(y>0,y<=0)
z1=cases(
"Condition 1"=x<0,
"Condition 2"=y<0,# only applies if x >= 0
"Condition 3"=TRUE
)
z2=cases(x<0,(x>=0 & y <0), (x>=0 & y >=0))
}))
xtabs(~x1+y1,data=df)
dd <- with(df,
try(cases(x<0,
x>=0,
x>1,
check.xor=TRUE)# let's be fussy
)
)
dd <- with(df,
try(cases(x<0,x>=0,x>1))
)
genTable(range(x)~dd,data=df)
# An example of the second kind of usage of the function:
# A construction of a non-smooth function
#
fun <- function(x)
cases(
x==0 -> 1,
abs(x)> 1 -> abs(x),
abs(x)<=1 -> x^2
)
x <- seq(from=-2,to=2,length=101)
plot(fun(x)~x)
# Demo of the new .default and .complete arguments
x <- seq(from=-2,to=2)
cases(a = x < -1,
b = x > 1,
.complete = TRUE)
cases(x < -1,
x > 1,
.complete = TRUE)
cases(1 <- x < -1,
3 <- x > 1,
.default = 2)
threshhold <- 5
d <- c(1:10, NaN)
d1 <- cases(
d > threshhold -> 1,
d <= threshhold -> 2
)
d2 <- cases(
is.na(d) -> 0,
d > threshhold -> 1,
d <= threshhold -> 2
)
# Leads to missing values because some of the conditions result in missing
# even though they could be 'captured'
d3 <- cases(
is.na(d) -> 0,
d > threshhold -> 1,
d <= threshhold -> 2,
na.rm=FALSE
)
d4 <- cases(
is.na(d) -> 0,
d > threshhold +2 -> 1,
d <= threshhold -> 2,
na.rm=FALSE
)
cbind(d,d1,d2,d3,d4)
cases(
d > threshhold,
d <= threshhold
)
cases(
is.na(d),
d > threshhold,
d <= threshhold
)
cases(
d > threshhold,
d <= threshhold,
.complete=TRUE
)
cases(
d > threshhold + 2,
d <= threshhold,
.complete=TRUE
)
Run the code above in your browser using DataLab