forked from lebebr01/SPSStoR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathComputeToR.r
33 lines (27 loc) · 931 Bytes
/
ComputeToR.r
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#' Compute to R
#'
#' Converts SPSS compute statements to variable creation in R.
#'
#' This function returns a matrix that highlights R syntax that mimics
#' the analysis done in SPSS.
#'
#' @param x SPSS syntax - read in by SPSStoR function
#' @export
compute_to_r <- function(x) {
x <- gsub('compute', '', x, ignore.case = TRUE)
x <- gsub("^\\s+|\\s+$", "", x)
x <- gsub("\\.$", "", x)
varname <- gsub("^\\s+|\\s+$", "", unlist(strsplit(x, '='))[1])
expr <- gsub("^\\s+|\\s+$", "", unlist(strsplit(x, '='))[2])
if(grepl('\\(', expr)) {
func <- tolower(unlist(strsplit(expr, '\\('))[1])
vars <- unlist(strsplit(expr, '\\('))[2]
expr <- paste(func, vars, sep = '(')
}
if(grepl('min|max|mean|sum', expr, ignore.case = TRUE)) {
expr <- gsub(')$', ', na.rm = TRUE)', expr)
}
finMat <- matrix(nrow = 1, ncol = 1)
finMat[1] <- paste0('x$', varname, ' <- ', expr)
finMat
}