我的问题:我有一个嵌套在 for 循环中的 if else 语句,并想保存它的每次迭代的值。
例如对于一些简单的数据,我尝试过的是:
s <- c(4, 8, 3) #a string with some values
l <- list() #the list where i want the output to be saved in
for (n in 1:length(s)) {
if (n==1) {
b1 <- 1:s[n]
print(b1)
l <- c(b1)}
else {
b2 <- (s[n-1]:s[n])
print(b2)
l <- c(b1=b1, b2=b2)}}
print() 输出的是我要保存的所有向量
[1] 1 2 3 4
[1] 4 5 6 7 8
[1] 8 7 6 5 4 3
但 l 只存储第一个向量(来自 if 语句)和 else 语句的最后一次迭代:
b11 b12 b13 b14 b21 b22 b23 b24 b25 b26
1 2 3 4 8 7 6 5 4 3
如何保存每次迭代?我已经尝试了几个小时但一无所获,非常感谢您的帮助!
最佳答案
试试这个
s <- c(4, 8, 3) #a string with some values
l <- list() #the list where i want the output to be saved in
for (n in 1:length(s)) {
if (n==1) {
b1 <- 1:s[n]
print(b1)
l[[length(l)+1]] <- c(b1)
}
else {
b2 <- (s[n-1]:s[n])
print(b2)
l[[length(l)+1]] <- b2
}
}
# [[1]]
# [1] 1 2 3 4
# [[2]]
# [1] 4 5 6 7 8
# [[3]]
# [1] 8 7 6 5 4 3
关于r - 在 R 中使用 if else 为 for 语句的每次迭代保存值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48512222/