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.

Examples

var1 <- rnorm(10)
toVariable(var1)
#> $values
#>  [1]  0.29175792 -1.62871780  1.23057064 -1.18716827 -0.67414752  0.08591617
#>  [7] -0.72281995  0.04399138  0.99794342  0.66066530
#> 
#> $type
#> [1] "numeric"
#> 
#> attr(,"class")
#> [1] "VariableDefinition"
toVariable(var1, name = "Random", description = "Generated in R")
#> $values
#>  [1]  0.29175792 -1.62871780  1.23057064 -1.18716827 -0.67414752  0.08591617
#>  [7] -0.72281995  0.04399138  0.99794342  0.66066530
#> 
#> $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"))
}