1

I have to perform a task 120 times in R and want to automate it using a for loop. Unfortunately, I have not succeeded in coding this.

Basically, I pull a vector from a list (the vectors' lengths differ) and transform it into a dataframe, I add a column with a tag for each column entry and eventually I add all these dataframes together to create one dataframe with two columns. One column contains the values and the other column contains the channel (c0, c1, ..., c118, c119) that each value belongs to. Below, the code can be seen for the first 3 steps. I want to make this into a for loop with 120 iterations.

    E0 <- data.frame(spk_list$elec_0)
    names(E0)[1] <- "Time"
    c0 <- rep("c0", each=length(E0))
    E0["Channel"] <- c0

    E1 <- data.frame(spk_list$elec_1)
    names(E1)[1] <- "Time"
    c1 <- rep("c1", each=length(E1))
    E1["Channel"] <- c1

    E2 <- data.frame(spk_list$elec_2)
    names(E2)[1] <- "Time"
    c2 <- rep("c2", each=length(E2))
    E2["Channel"] <- c2

E <- rbind(E0, E1, E2)

I hope someone can show me how this can be done, as I have been stuck for a while. Thank you very much in advance!

Jappa
  • 11
  • 1
  • 3
    Don't make individual, sequentially named data frames, [make a list of data frames](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames/24376207#24376207). – Gregor Thomas Apr 21 '21 at 19:36

1 Answers1

1

I can't test without any sample data, but I believe this is equivalent to your code:

# for loop version:

my_list = list()
for (i in 1:length(spk_list)) {
  my_list[[i]] = data.frame(
    Time = spk_list[[i]],
    Channel = paste0("c", i - 1)
  )
}
E = do.call(rbind, my_list)

This assumes that spk_list is already in the order you want. We don't need to worry about rep(), recycling will take care of repeating the Channel values appropriately.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294