3
\$\begingroup\$

I've written a stack implementation in R using S4 Classes. I would like feedback concerning anything with the application because it's my very first program in R. A main point of concern is how long it takes to create each method. The code is basically the same except for the body. It seems like there could be an easier way to create these class methods.

Stack <- setClass(
    # Name of Class #
    "Stack",

    # Define slots #
    slots = c(
        data = "vector"
    ),

    # Set default values of slots (optional) #
    prototype = list(
        data = c()
    )

)

# Create a method to add value to stack #
setGeneric(
    name = "push",
    def = function(object, value) {
        standardGeneric("push")
    }
)
setMethod(
    f = "push",
    signature="Stack",
    definition = function(object, value) {
        object@data <- c(object@data, value)
        return(object)
    }
)

# Create a method to remove value from stack #
setGeneric(
    name = "pop",
    def = function(object) {
        standardGeneric("pop")
    }
)
setMethod(
    f = "pop",
    signature = "Stack",
    definition = function(object) {
        # Sets the vector to all the values except the last one #
        object@data <- object@data[-length(object@data)]
        return(object)
    }
)

# Create a method to peek last value of stack #
setGeneric(
    name = "peek",
    def = function(object) {
        standardGeneric("peek")
    }
)
setMethod(
    f = "peek",
    signature = "Stack",
    definition = function(object) {
        return(object@data[length(object@data)])
    }
)

# Create a method to get size of the stack #
setGeneric(
    name = "size",
    def = function(object) {
        standardGeneric("size")
    }
)
setMethod(
    f = "size",
    signature = "Stack",
    definition = function(object) {
        return(length(object@data))
    }
)

# Create a method to return if size of stack is 0 #
setGeneric(
    name = "empty",
    def = function(object) {
        standardGeneric("empty")
    }
)
setMethod(
    f = "empty",
    signature = "Stack",
    definition = function(object) {
        return(length(object@data) == 0)
    }
)

Testing Implementation

stack <- Stack()
stack <- push(stack, 1)
stack <- push(stack, 2)
stack <- push(stack, 5)
stack <- pop(stack)
value <- peek(stack)
stack_size <- size(stack)
is_empty <- empty(stack)
\$\endgroup\$
  • \$\begingroup\$ A main point of concern is how long it takes to create each method. Takeaway from this is that R really isn't made with classes in mind :/ \$\endgroup\$ – JAD Nov 19 '19 at 8:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.