Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

S4 classes cannot be vectorized in R, as they do not have the necessary attributes to be treated as a vector. However, we can define methods for specific generic functions that help in performing operations on S4 objects stored in a list or a vector.

For example, consider a simple S4 class called "Person" with two slots, "name" and "age":

setClass("Person",
         slots = list(name = "character", age = "numeric"))

We can define a method to extract the names of a list of Person objects as follows:

setMethod("names", signature(x = "list"),
          function(x) sapply(x, function(y) y@name))

Now, we can use the generic function "names" to extract the names of a vector of Person objects:

p1 <- new("Person", name = "Alice", age = 25)
p2 <- new("Person", name = "Bob", age = 30)
persons <- c(p1, p2)

names(persons)

This will return a vector of names: "Alice" "Bob". Similarly, we can define methods for other generic functions like "length", "[[", and so on to perform operations on S4 objects stored in a vector or list.