library(RS)
Class(
"Asset",
# FIELDS
id = t_char,
company = t_char,
type = t_char,
price = t_dbl,
quantity = t_int,
# METHODS
value = function(.self) {
.self@price * .self@quantity
},
print = function(.self) {
cat("Asset ID:", .self@id, "\n")
cat("Name:", .self@company, "\n")
cat("Type:", .self@type, "\n")
cat("Price:", .self@price, "\n")
cat("Quantity:", .self@quantity, "\n")
cat("Total Value:", .self@value(), "\n")
}
)
Dataframes
A common pattern is reading tabular or document data from some source and populating class instances from it.
If you’re coming from Rust you may be familiar with something like serde for this sort of task.
With RS
, it is fairly easy to create multiple class instances from a table or JSON or similar source.
You can simply use the !!!
operator to pass a list of fields when initialising a class:
fields <- list(
id = "AAPL",
company = "Apple Inc.",
type = "Equity",
price = 150.0,
quantity = 10L
)
asset <- Asset(!!!fields)
asset@print()
Asset ID: AAPL
Name: Apple Inc.
Type: Equity
Price: 150
Quantity: 10
Total Value: 1500
This makes it simple to create multiple instances from a data-frame, for example:
Or if you like the tidyverse
, even simpler:
assets <- purrr::pmap(df, Asset)
You now have a list of Asset
classes ready to use.
Asset ID: AAPL
Name: Apple Inc.
Type: Equity
Price: 150
Quantity: 10
Total Value: 1500
Asset ID: GOOGL
Name: Alphabet Inc.
Type: Equity
Price: 2800
Quantity: 5
Total Value: 14000
Asset ID: AMZN
Name: Amazon.com Inc.
Type: Equity
Price: 3400
Quantity: 2
Total Value: 6800
You can of course do the same thing from any data source that for which you can store in R list
s, a common one might be JSON for example.