Entropy
Entropy

Reputation: 378

R -- Create Variable in List of Data Frames Based on a Sequence

I have created a series of data frames that are ordered in sequence (e.g., df1, df2, df3, df4, ...). I have pulled these data frames together into a list (ldf) and would now like to create a variable (z) that features the number associated with each data frame, such that the variable z for element df1 in ldf will equal 1, whereas z = 2 for df2 in ldf.

In reality I have several thousand data frames, but as an example, I put together the following code to build the data frames and wrap them into a list:

for (i in 1:4) {
  assign(paste0('df', i), data.frame(x = rep(1:100),
                                     y = seq(from = 1,
                                             to = 1000,
                                             length = 100)))
}

ldf <- list(df1, df2, df3, df4)

Borrowing a bit of code from another thread, I attempted to create the variable z with:

ldf <- lapply(ldf, function(x) {
  x$z = seq(1:4)
  return(x)
})

Not surprisingly, this just loops 1-4 repeatedly over the 100 observations in each data frame, rather than assigning 1 for df1, 2 for df2, 3 for df3, and 4 for df4 (as I desire).

If anyone who is more familiar with lists could help me figure this out I would be greatly appreciative.

Upvotes: 0

Views: 129

Answers (2)

IRTFM
IRTFM

Reputation: 263441

Does this address the request?

ldf$z <- seq_along(ldf)

Upvotes: 0

MrFlick
MrFlick

Reputation: 206411

If you want to iterate over two lists/vectors simultaneously, you can either use mapply() or Map. Here's code using the latter

Map(function(x,z) cbind(x,z=z), ldf, 1:4)

Upvotes: 2

Related Questions