Search code examples
rvariablesinitializationsparse-matrixvariable-declaration

R: Best way to replicate an object of same size and type as other?


Suppose you have some R object, such data.frame and Quanteda DFM sparse matrix. You want to replicate that object of the same size but no need to copy the content.

Is there some R command to replicate any object without copying the content? And if yes, do they work over sparse objects and non-sparse objects?


Solution

  • this will create the same data structure filled with NA

    data("iris")
    iris.mt <- iris[0, ]
    iris.mt[nrow(iris), ] <- NA
    
    str(iris.mt)
    'data.frame':   150 obs. of  5 variables:
     $ Sepal.Length: num  NA NA NA NA NA NA NA NA NA NA ...
     $ Sepal.Width : num  NA NA NA NA NA NA NA NA NA NA ...
     $ Petal.Length: num  NA NA NA NA NA NA NA NA NA NA ...
     $ Petal.Width : num  NA NA NA NA NA NA NA NA NA NA ...
     $ Species     : Factor w/ 3 levels "setosa","versicolor",..: NA NA NA NA NA NA NA NA NA NA ...