Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize N named, empty data frames into a list in R?

Tags:

dataframe

r

I want to initialize N named, empty data frames that have X rows and Y columns in each and put them in a list. I will fill them later by adding computed vectors. It’s a newbie question I know, but how does one do that? For example:

my.names <- c("G", "H", "J")
N <- 3
my.list <- ???  ## how?

(edited in light of replies ...) My reason for this approach is I have a big loop that creates N vectors each time through the loop. I need to save these results each iteration. I planned to do something like:

for(i in 1:N) my.list[[i]] <- my.vec[i]

on each pass in the loop. A 3D data frame or matrix would also do the same thing.

like image 805
Ernie Avatar asked May 18 '15 14:05

Ernie


People also ask

How do I initialize an empty data frame in R?

One simple approach to creating an empty DataFrame in the R programming language is by using data. frame() method without any params. This creates an R DataFrame without rows and columns (0 rows and 0 columns).

How do I create a list of data frames in R?

To create a list of Dataframes we use the list() function in R and then pass each of the data frame you have created as arguments to the function.

How do I create an empty dataset in R?

To create an empty Data Frame in R, call data. frame() function, and pas no arguments to it. The function returns an empty Data Frame with zero rows and zero columns.

Can you create an empty list in R?

To create an empty list in R programming, call list() function and pass no arguments in the function call.


1 Answers

Maybe you want to initialize a three-dimensional array instead?

myarr <- array(,dim=c(3,5,10))
for (j in 1:5) for (k in 1:10) myarr[,j,k] <- rnorm(3)

List of empty data.frames. I don't think there's a good reason to initialize a list of data.frames, but here's how it would be done:

An "empty" data.frame is created by data.frame():

setNames(replicate(3,data.frame()),my.names)
# $G
# data frame with 0 columns and 0 rows

# $H
# data frame with 0 columns and 0 rows

# $J
# data frame with 0 columns and 0 rows

A data.frame with rows and columns must have some values, for example NA:

nr  <- 4
nc  <- 4
ndf <- length(my.names)
setNames(replicate(ndf,as.data.frame(matrix(,nr,nc)),simplify=FALSE),my.names)
like image 104
Frank Avatar answered Oct 05 '22 23:10

Frank