0

Say i want to loop a list to the 10th element of said list. Can you tell me why code doesn't work?

loop <- function (list) {
  for (i in (list:list[[10]])) {
    df_i <- import(paste0(i))
  }
}
loop(list)

It returns:

Error in ord_dirs:ord_dirs[[10]] : NA/NaN argument
In addition: Warning messages:
1: In ord_dirs:ord_dirs[[10]] :
  numerical expression has 18 elements: only the first used
2: In pasardir(ord_dirs) : NAs introduced by coercion
3: In pasardir(ord_dirs) : NAs introduced by coercion
Roiadams
  • 21
  • 4
  • 1
    The `list:list[[10]]` should be `for i in in 1:10) {list[[i]]}` – akrun Apr 08 '21 at 18:35
  • 1
    Also, the `i` in the name `df_i` won't change as `i` changes, just like if I have a variable named `data` and I set `a <- "hello"`, it doesn't become `dhellothello`. You should probably put your results in a `list`. Perhaps `df_list <- lapply(list[1:10], import)`... but it's hard to tell. Is `list` actually of class `list`, or is it a character vector of filepaths, or something else? – Gregor Thomas Apr 08 '21 at 18:38
  • I'd suggest reading my answer at [How do I make a list of data frames?](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames/24376207#24376207) for discussion and examples. – Gregor Thomas Apr 08 '21 at 18:38
  • list is a character vector yes. – Roiadams Apr 08 '21 at 18:43

1 Answers1

0
loop <- function(list, x = 10) {

  df <- as.list(rep(NA, x))

  for (i in 1:x) {
    df[i] <- list[i]
  }

  df

}

list <- letters

loop(list)
Paul
  • 2,877
  • 1
  • 12
  • 28