Learn R Programming

crunch (version 1.30.4)

makeCaseVariable: Make a case variable

Description

The makeCaseVariable function derives a variable using values from other variables. These are evaluated in the order they are supplied in the list as the cases argument (they proceed in an IF, ELSE IF, ELSE IF, ..., ELSE fashion); the first one that matches selects the corresponding value from the case list. caseExpr() is a version that returns an expression that could be used when creating complex variables, see expressions for more details.

Usage

makeCaseVariable(..., cases, data = NULL, name)

caseExpr(..., cases)

Value

A VariableDefinition that will create the new case variable when assigned into the Dataset.

Arguments

...

a sequence of named expressions to use as cases as well as other properties to pass about the case variable (i.e. alias, description)

cases

a list of lists with each case condition to use each must include at least a name and an expression element. Cases may also include missing (logical) and numeric_value (numeric).

data

(optional) a crunch dataset to use. Specifying this means you don't have to put dataset$ in front of each variable name.

name

a character to use as the name of the case variable to create

Details

There are two ways to specify cases, but you must pick only one (note these two will produce the same case variable):

  1. When you just want to specify conditions, you can use named conditions: makeCaseVariable(case1=ds$v1 == 1, case2=ds$v2 == 2, name="new case")

  2. You can also use the cases argument, which is useful when you want to provide category ids, numeric values, or missingness: makeCaseVariable( cases=list( list(expression=ds$v1 == 1, name="case1"), list(expression=ds$v2 == 2, name="case2") ), name="new case" )

Rows in the dataset that do not match any of the provided "cases" will be assigned to an "else" category. By default, Crunch will use the system missing "No Data" category. Alternatively, you can provide an else case definition for these rows by including as the last "case" you provide one with its expression set to the string "else". See the examples for details.

Examples

Run this code
if (FALSE) {
makeCaseVariable(case1 = ds$v1 == 1, case2 = ds$v2 == 2, name = "new case")
makeCaseVariable(
    cases = list(
        list(expression = ds$v1 == 1, name = "case1"),
        list(expression = ds$v2 == 2, name = "case2")
    ),
    name = "new case"
)

# different ways to specify else cases
makeCaseVariable(
    cases = list(
        list(expression = ds$v1 == 1, name = "case1"),
        list(expression = ds$v2 == 2, name = "case2"),
        list(expression = "else", name = "other")
    ),
    name = "new case"
)
makeCaseVariable(case1 = ds$v1 == 1, case2 = ds$v2 == 2, other = "else", name = "new case")

# the dataset can be specified with data=
makeCaseVariable(case1 = v1 == 1, case2 = v2 == 2, data = ds, name = "new case")
}

Run the code above in your browser using DataLab