2

This may be a trivial question, given I only have a few days' experience using R but basically i'd like to create a named list of data frames. I've seen a bunch of questions and answers dealing with only 2 data frames e.g

dataList <- list(x=data.frame1, y=data.frame2)

However i'm working with 48 data frames in this program and would like to know a more elegant way of creating a named list of 48 elements without actually explicitly naming all 48 of my data frames (which is what i've currently got):

dataList <- list(forecasted.data0=forecasted.data0, forecasted.data1=forecasted.data1, ...) and so on 46 more times.

Cnerb
  • 171
  • 1
  • 2
  • 4

2 Answers2

4

Use the names or setNames function

> x <- as.list(rnorm(5))
> x
[[1]]
[1] -1.404512

[[2]]
[1] 0.927126

[[3]]
[1] 1.055555

[[4]]
[1] -1.718295

[[5]]
[1] 0.5154312

> names(x) <- paste0("forecasted.data.", seq(0, length(x) - 1))
> x
$forecasted.data.0
[1] -1.404512

$forecasted.data.1
[1] 0.927126

$forecasted.data.2
[1] 1.055555

$forecasted.data.3
[1] -1.718295

$forecasted.data.4
[1] 0.5154312
sebastian-c
  • 15,057
  • 3
  • 47
  • 93
1

Would this work ?

forecasted.data0=data.frame(1)
forecasted.data1=data.frame(2)

n=ls()[grepl("^forecasted.data.*",ls())]
l=sapply(n, function(x) get(x))
names(l)=n

You can replace sapply with lapply if you prefer ...

user3507085
  • 700
  • 5
  • 17
  • It didn't necessarily work, but that may be down to my inexperience with R. Thanks for your contribution – Cnerb Sep 15 '16 at 07:57