Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8347193
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T07:17:10+00:00 2026-06-09T07:17:10+00:00

I have defined an S4 class called cell , instances of which I would

  • 0

I have defined an S4 class called cell, instances of which I would like to assign to a 3×3 matrix (3×3 is chosen for definiteness). The following code works in R version 2.15.1 and reproduces R’s behavior in a simple case. I find that I can assign objects of type cell to a matrix whose entries are first initialized to empty lists with matrix(list(),3,3), after which I assign new objects of type cell to the entries. The question is: why does it work?

    setClass("cell", representation = representation(       
        A="numeric",  # a field
        B="numeric")) # another one

    # initialize the cell
    setMethod("initialize", "cell", function(.Object, a,b) {
        .Object@A <- a;
        .Object@B <- b;
    .Object})

    createGrid <- function(a,b) {
        grid <- matrix(list(),3,3)  # note initialization to list()
        for (i in 1:3 )
            for (j in 1:3)
                grid[[i,j]] <- new("cell",j,i);
        grid}

This is a sample session:

    > source("stackoverflow.R")
    > grid <- createGrid(1,2)
    > grid[[1,3]]
    An object of class "cell"
    Slot "A":
    [1] 3

    Slot "B":
    [1] 1

    > grid[[2,3]]
    An object of class "cell"
    Slot "A":
    [1] 3

    Slot "B":
    [1] 2

Modifying createGrid() by changing the empty list assignment to grid<- matrix(0,3,3) will generate an error:

    > grid <- createGrid0(1,2)
    Error in grid[[i, j]] <- new("cell", j, i) : 
      more elements supplied than there are to replace

This is not surprising, but it did lead me to the working code.
The following attempt to define a 3×3 matrix of cells usingnew() fails:

    > grid <- matrix(new("cell",1,2),3,3)
    Error in as.vector(data) : 
      no method for coercing this S4 class to a vector

The question is, why does the first work?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T07:17:14+00:00Added an answer on June 9, 2026 at 7:17 am

    Not really answering the question, but…

    Usually it pays to think in terms of vectors, so instead of ‘cell’ maybe ‘Cell’ that represents the entire matrix. Here’s an implementation. The idea is that Cell extends matrix, with vectors that contain additional values.

    setClass("Cell", representation("matrix", A="numeric", B="numeric"))
    

    We constrain A and B to have the same length with a validity function

    setValidity("Cell", function(object) {
        msg <- NULL
        if (length(object@A) != length(object@B))
            msg <- c(msg, "'A' and 'B' must be the same length")
        if (is.null(msg)) TRUE else msg
    })
    

    and make a constructor that initialized the matrix of Cell with indicies into A and B.

    Cell <- function(A, B, ...)
        new("Cell", matrix(seq_along(A), ...), A=A, B=B)
    

    The ... arguments are the non-data arguments (nrow, ncol, dimnames, etc) of matrix().

    We get some functionality for free (e.g., dim, nrow, ncol, length, …) but need to implement sub-setting and, presumably, other operations. For single-bracket sub-setting, we pass the operation down to the underlying matrix, and then use the resulting indicies to sub-set A and B, creating a new Cell instance with the updated values

    setMethod("[", "Cell", function(x, i, j, ..., drop=TRUE) {
        m <- callNextMethod()
        initialize(x, m, A=x@A[m], B=x@B[m])
    })
    

    Finally, implement a show method

    setMethod(show, "Cell", function(object) {
        cat("class:", class(object), "\n")
        cat("dim:", dim(object), "\n")
        m <- object@.Data
        m[] <- object@A
        cat("A:\n"); print(m)
        m[] <- object@B
        cat("B:\n"); print(m)
    })
    

    And then in action:

    > Cell(1:6, 6:1, 3, 2)[c(3, 1), 2:1]
    class: Cell 
    dim: 2 2 
    A:
         [,1] [,2]
    [1,]    6    3
    [2,]    4    1
    B:
         [,1] [,2]
    [1,]    1    4
    [2,]    3    6
    

    There seem to be several benefits to this implementation. A matrix is supposed to have a single type, and that is the case here (with cell, the elements of the matrix are lists and so could contain any data). There’s quite a bit of functionality inherited from matrix. Presumably you want to implement operations on your Cell matrix, and the underlying vectors A, B can be manipulated efficiently, e.g. via the group generic Arith,

    setMethod("Arith", c("Cell", "Cell"), function(e1, e2) {
        A <- callGeneric(e1@A, e2@A)
        B <- callGeneric(e1@B, e2@B)
        initialize(e1, e1@.Data, A=A, B=B)
    })
    

    and then

    > c1 = Cell(1:6, 6:1, 3, 2)
    > c2 = Cell(6:1, 1:6, 3, 2)
    > c1 + c2
    class: Cell 
    dim: 3 2 
    A:
         [,1] [,2]
    [1,]    7    7
    [2,]    7    7
    [3,]    7    7
    B:
         [,1] [,2]
    [1,]    7    7
    [2,]    7    7
    [3,]    7    7
    > c1 * c2
    class: Cell 
    dim: 3 2 
    A:
         [,1] [,2]
    [1,]    6   12
    [2,]   10   10
    [3,]   12    6
    B:
         [,1] [,2]
    [1,]    6   12
    [2,]   10   10
    [3,]   12    6
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a class called MainGame, which is defined like this in my .h:
I have a class called Path for which there are defined about 10 methods,
In a class called 'Quality' I have the following constants defined: class Quality <
I Have a View stronger Typed, of my class called Cliente , Defined like
I have a class called imageResizing. It has a member, MAX_WIDTH_ORIGINAL_IMG which is defined
I have a class (called Employee. non static) defined in a class library. I
I have defined the following class using COM to use the IGroupPolicyObject using C#.NET:
I have defined a ConfigurationProperty class, which is basicly a key-value pair (with key
I have defined an Event class: Event and all the following classes inherit from
Let's say I have defined the following class: public abstract class Event { public

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.