oercim
oercim

Reputation: 1848

R-creating multiple data frames with names

I want to create 100 empty data frames with names

Each data frame will have 2 columns where

How can I create such data frames using R. I will be very glad for any help. Many thanks.

Upvotes: 2

Views: 3361

Answers (1)

akrun
akrun

Reputation: 887991

We can create the empty 'data.frames' in a list using replicate and change the column names with Map

n <- 100
lst <- replicate(n,data.frame(y=character(), x=numeric(),
                     stringsAsFactors=FALSE), simplify=FALSE)

names(lst) <- paste0('df', 1:n)
nmy <- paste0('y', 1:n)
nmx <- paste0('x', 1:n)
lst1 <- Map(function(x,y,z) {names(x) <- c(y,z); x}, lst, nmy, nmx)

Or

lst1 <- Map(setNames, lst, as.data.frame(rbind(nmy,nmx)))


str(lst1, list.len=3)
#List of 100
# $ df1  :'data.frame': 0 obs. of  2 variables:
#  ..$ y1: chr(0) 
#  ..$ x1: num(0) 
# $ df2  :'data.frame': 0 obs. of  2 variables:
#  ..$ y2: chr(0) 
#  ..$ x2: num(0) 
# $ df3  :'data.frame': 0 obs. of  2 variables:
#  ..$ y3: chr(0) 
#  ..$ x3: num(0) 
# [list output truncated]

Upvotes: 6

Related Questions