library(macro)
########################################################################
# Example 1: Hello World Macro
########################################################################
# Get path to demo macro program
src <- system.file("extdata/Demo1.R", package = "macro")
# Display source code
# - This is the macro input code
cd <-readLines(src)
cat(paste(cd, "\n"))
# #%let a <- 1
# #%if (&a. == 1)
# print("Hello World!")
# #%else
# print("Goodbye!")
# #%end
# Macro Execute Source Code
# - Results displayed below
msource(src)
# ---------
# print("Hello World!")
# ---------
# [1] "Hello World!"
########################################################################
# Example 2: Perform correlation analysis between variables in MTCARS
########################################################################
# Get path to demo macro program
src <- system.file("extdata/Demo2.R", package = "macro")
# Display source code
cd <- readLines(src)
cat(paste(cd, "\n"))
# #% Macro for Correlation Analysis
# #%macro get_correlation(dat, xvar, yvars)
#
# # Perform Analysis ------------------------------------
#
# #%do idx = 1 %to %sysfunc(length(&yvars))
#
# #%let yvar <- %sysfunc(&yvars[&idx])
# #%let xdat <- &dat$&xvar
# #%let ydat <- &dat$&yvar
# # Correlation between &xvar and &yvar
# anl_&yvar <- data.frame(XVAR = "&xvar",
# YVAR = "&yvar",
# COR = cor(`&xdat`, `&ydat`,
# method = "pearson"))
# #%end
#
#
# # Bind Results ----------------------------------------
#
# #%let anl_lst <- %sysfunc(paste0("anl_", &yvars, collapse = ", "))
#
# # Combine all analysis data frames
# final <- rbind(`&anl_lst`)
#
# # Print Results
# print(final)
#
# #%mend
#
# #% Call Macro
# #%get_correlation(mtcars, mpg, c("cyl", "disp", "drat"))
# Macro Execute Source Code
msource(src)
# ---------
# # Perform Analysis ------------------------------------
#
#
# # Correlation between mpg and cyl
# anl_cyl <- data.frame(XVAR = "mpg",
# YVAR = "cyl",
# COR = cor(mtcars$mpg, mtcars$cyl,
# method = "pearson"))
#
# # Correlation between mpg and disp
# anl_disp <- data.frame(XVAR = "mpg",
# YVAR = "disp",
# COR = cor(mtcars$mpg, mtcars$disp,
# method = "pearson"))
#
# # Correlation between mpg and drat
# anl_drat <- data.frame(XVAR = "mpg",
# YVAR = "drat",
# COR = cor(mtcars$mpg, mtcars$drat,
# method = "pearson"))
#
#
# # Bind Results ----------------------------------------
#
#
# # Combine all analysis data frames
# final <- rbind(anl_cyl, anl_disp, anl_drat)
#
# # Print Results
# print(final)
#
# ---------
# XVAR YVAR COR
# 1 mpg cyl -0.8521620
# 2 mpg disp -0.8475514
# 3 mpg drat 0.6811719
#
Run the code above in your browser using DataLab