R objects are converted to Crunch objects using the following rules:

toVariable(x, ...)

# S4 method for CrunchVarOrExpr
toVariable(x, ...)

# S4 method for character
toVariable(x, ...)

# S4 method for numeric
toVariable(x, ...)

# S4 method for factor
toVariable(x, ...)

# S4 method for Date
toVariable(x, ...)

# S4 method for POSIXt
toVariable(x, ...)

# S4 method for AsIs
toVariable(x, ...)

# S4 method for VariableDefinition
toVariable(x, ...)

# S4 method for logical
toVariable(x, ...)

# S4 method for labelled
toVariable(x, ...)

# S4 method for haven_labelled
toVariable(x, ...)

# S4 method for labelled_spss
toVariable(x, ...)

# S4 method for haven_labelled_spss
toVariable(x, ...)

Arguments

x

An R vector you want to turn into a Crunch variable

...

Additional metadata fields for the variable, such as "name" and "description". See the API documentation for a complete list of valid attributes.

Value

A VariableDefinition object. To add this to a dataset, either assign it into the dataset (like ds$newvar <- toVariable(...)) or call addVariables(). If you're adding a column of data to a dataset, it must be as long as the number of rows in the dataset, or it may be a single value to be recycled for all rows.

Details

  • Character vectors are converted into Crunch text variables

  • Numeric vectors are converted into Crunch numeric variables

  • Factors are converted to categorical variables

  • Date and POSIXt vectors are converted into Crunch datetime variables

  • Logical vectors are converted to Crunch categorical variables

  • VariableDefinition()s are not converted, but the function can still append additional metadata

If you have other object types you wish to convert to Crunch variables, you can declare methods for toVariable.

See also

Examples

var1 <- rnorm(10)
toVariable(var1)
#> $values
#>  [1]  1.1484116 -1.8218177 -0.2473253 -0.2441996 -0.2827054 -0.5536994
#>  [7]  0.6289820  2.0650249 -1.6309894  0.5124269
#> 
#> $type
#> [1] "numeric"
#> 
#> attr(,"class")
#> [1] "VariableDefinition"
toVariable(var1, name = "Random", description = "Generated in R")
#> $values
#>  [1]  1.1484116 -1.8218177 -0.2473253 -0.2441996 -0.2827054 -0.5536994
#>  [7]  0.6289820  2.0650249 -1.6309894  0.5124269
#> 
#> $type
#> [1] "numeric"
#> 
#> $name
#> [1] "Random"
#> 
#> $description
#> [1] "Generated in R"
#> 
#> attr(,"class")
#> [1] "VariableDefinition"
if (FALSE) {
ds$random <- toVariable(var1, name = "Random")
# Or, this way:
ds <- addVariables(ds, toVariable(var1, name = "Random"))
}