问题
please do let me know if this question is too general.
I'm trying to implement a for loop with a nested for loop. Every time the for loop runs, it will either print two integer values or next onto the next iteration.
As a result, I have outputs from the for loop that looks like this:
[1] 10 57
[1] 10 58
[1] 10 59
[1] 10 63
[1] 10 64
[1] 10 67
[1] 10 68
[1] 10 69
[1] 10 70
[1] 10 71
[1] 10 72
[1] 10 75
[1] 10 76
[1] 10 77
[1] 10 78
[1] 10 79
[1] 10 80
[1] 10 82
[1] 10 86
[1] 10 87
[1] 10 90
I was wondering what are best practices for inserting thse pairs of integers in lists. Since there is a for loop with an iterator of i nested inside a for loop with an iterator of j, I can not just write:
list[[i]] <- c(i, j)
回答1:
Say indx is a vector with some random values:
[1] 58 61 67 69 70 72 78 79 84 85
The for loop I would write:
for(i in 1:3){
for(j in indx){
print(c(i, j))
}
}
Would produce the following output (without assigning it to an object):
[1] 1 58
[1] 1 61
[1] 1 67
[1] 1 69
[1] 1 70
[1] 1 72
[1] 1 78
[1] 1 79
[1] 1 84
[1] 1 85
[1] 2 58
[1] 2 61
...
[1] 3 84
[1] 3 85
If you're trying to save it into a vector, this code works for you:
myls <- vector()
for(i in 1:3){
for(j in indx){
myls <- c(myls, c(i, j))
}
}
EDIT
Based on OP's additional comment, I wanted to show you another way to directly get a list, by appending each combination of i and j as a list element:
indx <- c(58, 61, 67, 69, 70, 72, 78, 79, 84, 85)
myls <- list()
for(i in 1:3){
for(j in indx){
myls <- c(myls, list(c(i, j)))
}
}
Your myls variable is now a list:
myls[1:3]
[[1]]
[1] 1 58
[[2]]
[1] 1 61
[[3]]
[1] 1 67
来源:https://stackoverflow.com/questions/50186955/add-two-integers-to-each-element-of-a-list-in-a-for-loop