0

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.

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

Does this address the request?

ldf$z <- seq_along(ldf)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.