【发布时间】:2017-02-01 00:19:31
【问题描述】:
for(i in 1:na) {
b1=which(IFUT[,1]==format(data1[i]))
b2=which(IFUT[b1,2]==format(data2[i])
b3=which(IFUT[b1[b2],3]=="12:30:00.000")
????????=b1[b2[b3]]
如何将输出 b1[b2[b3]] 存储在这种循环的列表中?
【问题讨论】:
for(i in 1:na) {
b1=which(IFUT[,1]==format(data1[i]))
b2=which(IFUT[b1,2]==format(data2[i])
b3=which(IFUT[b1[b2],3]=="12:30:00.000")
????????=b1[b2[b3]]
如何将输出 b1[b2[b3]] 存储在这种循环的列表中?
【问题讨论】:
首先,做一个列表来存储结果
list_res = list() #empty list
第二,放循环
#your for loop here
list_res 的每个元素,它是一个向量(因为它包含 3 个元素) 因此,在循环结束时,我们创建一个向量来存储 3 个元素 B1、B2、B3
#put these following lines in the for loop
sub_vector = c()#empty vector
sub_vector = c(B1, B2, B3) #one element in the list
list_res[[i]] = sub_vector # append it to the list
然后,我们得到了 list_res 作为结果。
【讨论】:
查看 lapply 函数。
https://stat.ethz.ch/R-manual/R-devel/library/base/html/lapply.html
它的输出是一个结果列表,它比 for 循环运行得更快。
如果您需要将该列表转换为向量(您可能会这样做),请查看 do.call 函数。
https://www.r-bloggers.com/concatenating-a-list-of-data-frames/
如果这太复杂了,那么你可能应该声明一个向量并附加到它上面,只要确保在循环之外声明向量:
VectorA <- c()
for(i in x:y){
#Your Loop + append to vector
}
【讨论】: