Saturday, August 6, 2016

R Code Snippets

Handling properties file

Sample File: test.properties
key1=value1
key2=value2
key3=value3


Read properties from file
filePath = "/path/to/properties/file"
props = read.table(filePath, header=FALSE, sep="=", row.names=1, strip.white=TRUE, na.strings="NA", stringsAsFactors=FALSE)


Properties can be accessed using their keys by props[key, 1]

Example:-
value = props["key1", 1]
print(value)


Prints value1

Loading choices for a Shiny app drop down from properties file
loadChoicesFromPropertiesFile = function(filePath) {
  props = read.table(filePath, header=FALSE, sep="=", row.names=1, strip.white=TRUE, na.strings="NA", stringsAsFactors=FALSE)
  choices = list()
  for(key in row.names(props)) {
    choices[[paste0(props[key, 1])]] = key
  }
  return (choices)
}


Defining the select drop down in ui.R
myOptions = loadChoicesFromPropertiesFile(filePath)
selectInput("myOptions", label = h4("Options"), choices = myOptions)

No comments:

Post a Comment