Search code examples
rvectorabstractpolynomialscoefficients

Is there a way that I can store a polynomial or the coefficients of a polynomial in a single element in an R vector?


I want to create an R function that generates the cyclic finite group F[x].

Basically, I need to find a way to store polynomials, or at the least a polynomial's coefficients, in a single element in an R vector.

For example, if I have a set F={0,1,x,1+x}, I would like to save these four polynomials into an R vector such as

F[1] <- 0 + 0x
F[2] <- 1 + 0x
F[3] <- 0 + x
F[4] <- 1 + x

But I keep getting the error: "number of items to replace is not a multiple of replacement length"

Is there a way that I can at least do something like:

F[1] <- (0,0)
F[2] <- (1,0)
F[3] <- (0,1)
F[4] <- (1,1)

For reference in case anyone is interested in the mathematical problem I am trying to work with, my entire R function so far is

gf <- function(q,p){

  ### First we need to create an irreducible polynomial of degree p
  poly <- polynomial(coef=c(floor(runif(p,min=0,max=q)),1)) #This generates the first polynomial of degree p with coefficients ranging between the integer values of 0,1,...,q
  for(i in 1:(q^5*p)){ #we generate/check our polynomial a sufficient amount of times to ensure that we get an irreducible polynomial
    poly.x <- as.function(poly) #we coerce the generated polynomial into a function
    for(j in 0:q){ #we check if the generated polynomial is irreducible
      if(poly.x(j) %% q == 0){ #if we find that a polynomial is reducible, then we generate a new polynomial
        poly <- polynomial(coef=c(floor(runif(p,min=0,max=q)),1)) #...and go through the loop again
      }
    }
  }
  list(poly.x=poly.x,poly=poly)

  ### Now, we need to construct the cyclic group F[x] given the irreducible polynomial "poly"
  F <- c(rep(0,q^p)) #initialize the vector F
  for(j in 0:(q^p-1)){
    #F[j] <- polynomial(coef = c(rep(j,p)))
    F[j] <- c(rep(0,3))  
  }
  F
}

Solution

  • Make sure F is a list and then use [[]] to place the values

    F<-list()
    F[[1]] <- c(0,0)
    F[[2]] <- c(1,0)
    F[[3]] <- c(0,1)
    F[[4]] <- c(1,1)
    

    Lists can hold heterogeneous data types. If everything will be a constant and a coefficient for x, then you can also use a matrix. Just set each row value with the [row, col] type subsetting. You will need to initialize the size at the time you create it. It will not grow automatically like a list.

    F <- matrix(ncol=2, nrow=4)
    F[1, ] <- c(0,0)
    F[2, ] <- c(1,0)
    F[3, ] <- c(0,1)
    F[4, ] <- c(1,1)