Created
March 1, 2017 19:46
-
-
Save ZhangYet/b705b5065768e22434220669d6c5ce1c to your computer and use it in GitHub Desktop.
demo_st_deparse.R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require('sourcetools') | |
get_index <- function(col, width, control) { | |
if (control == 'forward') { | |
temp <- col[col<=width] | |
return(which(col==max(temp))) | |
} else { | |
temp <- col[col>=width] | |
return(which(col==min(temp))) | |
} | |
} | |
st_deparce <- function(tokens, width.cutoff, control) { | |
if (max(tokens$column) <= width.cutoff) { # TODO: wrong boundary condition | |
return(paste(tokens$value, collapse="")) | |
} | |
index <- get_index(tokens$column, width.cutoff, control) | |
if (tokens$width[index]>1) { | |
if (control == 'forward') { | |
index <- index - 1 | |
} else { | |
index <- index + 1 | |
} | |
} | |
if (index >= nrow(tokens) || index == 0) { | |
return(paste(tokens$value, collapse = "")) | |
} | |
rest <- tokens[(index+1):nrow(tokens), ] | |
rest$column <- rest$column - min(rest$column) + 1 | |
st_deparce(rest, width.cutoff, control) | |
print(c(paste(tokens$value[1:index], collapse = ""))) | |
return(c(paste(tokens$value[1:index], collapse = ""), | |
st_deparce(rest, width.cutoff, control))) | |
} | |
test <- "lm( weight ~ group )" | |
test_tokens <- tokenize_string(test) | |
test_tokens$width <- lapply(test_tokens$value, nchar) | |
res1 <- st_deparce(test_tokens, 7, 'forward') | |
res2 <- st_deparce(test_tokens, 7, 'backward') | |
print(paste(res1, collapse = '\n')) | |
# lm( | |
# weight | |
# ~ | |
# group ) | |
print(paste(res2, collapse = '\n')) | |
# lm( weight | |
# ~ group | |
# ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment