我试图将函数应用于for循环中的矩阵。输出也应该是在循环的每一步都改变的矩阵。以下代码解释了我的问题:
I1=apply(I0, 1, func1)
I2=apply(I1, 1, func1)
I3=apply(I2, 1, func1)
.
.
I10=apply(I9, 1, func1)
I0,I1,... I10均为4X10矩阵,func 1为预定义函数。我一直试图用循环来解决这个问题。我无法找到相关信息。我需要这样的东西:
for(i in 1:10){
I[i]=apply(I[i-1],1,func1)
}
答案 0 :(得分:1)
有两种简单的方法:
1-使用get
和assign
:
# How get and assign work:
x0 = 10
get(paste0("x", 0)) # get the variable passed as a string argument - returns 10
assign(paste0("x", 0), 20) # assign 20 to x
print(x0) #20
# And.. the recursion
x0 = 2 # recursive initialization
for(i in 1:5) {
previousValue = get(paste0("x", i-1))
thisValue = previousValue * 2
assign(paste0("x", i), thisValue)
}
2-使用list
的魔力:
x0 = 2 # recursive initialization
myResults = list(x0)
# Now, the recursion!
for(i in 1:5) {
thisValue = myResults[[i]]
nextValue = c(thisValue * 2) # Some random calculation, use your function instead
myResults[[i+1]] = nextValue # Now add to the list
}