【问题标题】:how to store results into a for loop of matrices applying a function at each step of the loop?如何将结果存储到矩阵的for循环中,在循环的每个步骤中应用一个函数?
【发布时间】:2015-12-01 03:36:26
【问题描述】:

我正在尝试将函数应用于 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)
   }

【问题讨论】:

  • 这不是运气问题,但您确实需要定义 I0 以使其具有任何意义。构造一个维度为c(4,10,10) 的数组或矩阵列表会更有意义。如果它是一个数组,内部命令将是 I[,,i]=apply(I[,,i-1],1,func1),如果是一个列表,则 I[[i]]=apply(I[[ i-1 ],1,func1) ... 您需要放弃拥有单独命名对象的概念。

标签: r function for-loop matrix


【解决方案1】:

有两种简单的方法:

1- 使用getassign

# 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 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    相关资源
    最近更新 更多