1

I'm trying to do a simple for loop on multiple data frames and save the output (from all data frames) to one list.

Here is example data:

# Two example data frames (variables x and y)
a <- data.frame(x=rnorm(1:100, 10, 1), y=1:100)
b <- data.frame(x=rnorm(1:100, 500, 50), y=1:100)

# Merging data frames to a list, which we aim to loop through
data_frame_list <- list(a, b)

# Desired list
new_list <- list()

# The loop
# I want two simple values from each data frame (value1 and value2)
for(i in data_frame_list) {
     for(j in 1:5) {
          value1 = i[j,1]
          value2 = i[j,2]
          new_list[i] <- cbind(value1, value2)
     }
}

So from each data frame i want value1 and value 2 for all the j values (1 to 5). I'd like to have all the extracted data in a list (new_list).

Thanks for help

3 Answers 3

2

The other answers are helpful, but I wanted to try to help you fix your for loop.

for(i in 1:length(data_frame_list)) {
   for(j in 1:5) {
      value1 = data_frame_list[[i]][j,1]
      value2 = data_frame_list[[i]][j,2]
      new_list[[5*(i-1)+j]] = c(value1, value2)
   }
}

A few differences from your code:

  • You need to assign to the next element of the list by subsetting using [[, i.e. double brackets, instead of single brackets, [. In your code, I was getting a " invalid subscript type 'list'" error, which I'm pretty sure was due to this.
  • cbind creates a data structure that you might not want -- if you just want the values, might be easier to create a vector using c()
  • in your code, the new_list values are replaced on the second iteration of the outer loop. In order to fix this, I needed to access the data frames within the loop using subsetting. This allowed me to extend the length of the list so that it appends the elements of the second data frame.

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

1

Are you trying to select the first 5 columns of data frames a and b?

If so, try this:

new_list <- cbind(a[, 1:5], b[, 1:5])

Comments

1

If I read correctly your problem, you are trying to get the first 5 rows of data (including the columns) from each element of the list data_frame_list. If so, then this might help:

for(i in data_frame_list) { new_list <- i[1:5, ]} It provides a new list with ONLY the first 5 rows (columns included) of each element in the first list. It that list were to get bigger it should incorporate the first five elements of each new list.

Hope it helps!

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.