For loop in multiple of fives

Viewed 45

Thanks to @akrun, I could run my previous question about merging and creating tables with loop. Merge and create tables using a loop

However, because my laptop only has 16GB of RAM, I couldn't run the large dataset using the code. So, instead of merging 100 times, I decided to separate the process, and do it step by step using a for-loop.

I was going to create 20 lists of data using for loop, but then I couldn't find a way to make this happen.

To be specific, I would run the following 20 lines of code manually without using a for loop.

list1 <- mget(paste0("", 1:5))

list2 <- mget(paste0("", 6:10))

list3 <- mget(paste0("", 11:15))

list4 <- mget(paste0("", 16:20))

list5 <- mget(paste0("", 21:25))

...

list20 <- mget(paste0("", 96:100))

How would I write for loop in this case?

I tried to find a way to do this (for example as below), but I am getting an error.

for(i in 1:20){
  list[i] <- mget(paste0("",5*i-4:5*i))
}

Thanks in advance for all your help!

1 Answers

There are multiple ways to create the list. Either use split with %/%

fulllst <- lapply(split(as.character(1:100), (1:100-1) %/% 5 + 1), mget)

Or use the same code in OP's post by wrapping the code with () to avoid evaluation based on precedence of operators

# create an empty list to store the output
lstout <- vector('list', 20)
# loop over the sequence and add the `()` for `(5* i- 4)` and similarly for (5*i)
for(i in 1:20) 
    lstout[[i]] <- mget(as.character((5 *i -4):(5*i)))

Use print to find the difference

> for(i in 1:20) print((5 *i -4):(5*i))
[1] 1 2 3 4 5
[1]  6  7  8  9 10
[1] 11 12 13 14 15
[1] 16 17 18 19 20
[1] 21 22 23 24 25
[1] 26 27 28 29 30
[1] 31 32 33 34 35
[1] 36 37 38 39 40
[1] 41 42 43 44 45
[1] 46 47 48 49 50
[1] 51 52 53 54 55
[1] 56 57 58 59 60
[1] 61 62 63 64 65
[1] 66 67 68 69 70
[1] 71 72 73 74 75
[1] 76 77 78 79 80
[1] 81 82 83 84 85
[1] 86 87 88 89 90
[1] 91 92 93 94 95
[1]  96  97  98  99 100
> for(i in 1:20) print(5 *i -4:5*i)
[1] 1 0
[1] 2 0
[1] 3 0
[1] 4 0
[1] 5 0
[1] 6 0
[1] 7 0
[1] 8 0
[1] 9 0
[1] 10  0
[1] 11  0
[1] 12  0
[1] 13  0
[1] 14  0
[1] 15  0
[1] 16  0
[1] 17  0
[1] 18  0
[1] 19  0
[1] 20  0

ie. if we don't use the () the evaluation will be

i <- 1
(5 * i) - (4:5 * i)
[1] 1 0
# instead of 
(5 * i -4):(5 * i)
[1] 1 2 3 4 5

The operator precendence is showed in ?Syntax

:: :::  access variables in a namespace
$ @ component / slot extraction
[ [[    indexing
^   exponentiation (right to left)
- + unary minus and plus
:   sequence operator
%any% |>    special operators (including %% and %/%)
* / multiply, divide
+ - (binary) add, subtract
....
Related