R/R-to-variable.R
toVariable.Rd
R objects are converted to Crunch objects using the following rules:
toVariable(x, ...)
# S4 method for class 'CrunchVarOrExpr'
toVariable(x, ..., derived = derivedVariableDefault())
# S4 method for class 'character'
toVariable(x, ...)
# S4 method for class 'numeric'
toVariable(x, ...)
# S4 method for class 'factor'
toVariable(x, ...)
# S4 method for class 'Date'
toVariable(x, ...)
# S4 method for class 'POSIXt'
toVariable(x, ...)
# S4 method for class 'AsIs'
toVariable(x, ...)
# S4 method for class 'VariableDefinition'
toVariable(x, ...)
# S4 method for class 'logical'
toVariable(x, ...)
# S4 method for class 'labelled'
toVariable(x, ...)
# S4 method for class 'haven_labelled'
toVariable(x, ...)
# S4 method for class 'labelled_spss'
toVariable(x, ...)
# S4 method for class 'haven_labelled_spss'
toVariable(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.
Logical, when FALSE
indicates a variable should be
materialized on creation (saved as data, which can have performance benefits
in certain situation) and when TRUE
indicates it should remain derived
(saved as an expression that can update along with the underlying data)
Defaults to TRUE
unless envOrOption('crunch.default.derived')
has been set.
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.
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
.
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) { # \dontrun{
ds$random <- toVariable(var1, name = "Random")
# Or, this way:
ds <- addVariables(ds, toVariable(var1, name = "Random"))
} # }