R

时间:2016-06-20 20:07:37

标签: r list

我一直在尝试创建一个列表,其中包含具有相同值的向量坐标。

示例:对于向量Points = (2, 2, 3, 6, 3, 6, 3),具有相同值的坐标是(1,2),(3,5,7)和(4,6)。所以输出应该是

[[1]]
1 2

[[2]]
3 5 7

[[3]]
4 6

只是为了说明这个功能的必要性:我试图用多个起点来模拟随机游走。一旦任何给定的链相互碰撞,索引最小的链将被更新。向量Points是在某个时间步t的所有步行的位置。我需要在每个时间步骤验证哪些链具有相同的值,以便仅更新索引最小的链。在此特定示例中,只有链1,3和4将在瞬时t+1更新。

1 个答案:

答案 0 :(得分:0)

也许是这样的:

X = c(2, 3, 4 )
Y = c(4, 3 ,5)
Z = c(8, 8 , 9, 6)
W = c(3, 3, 7,4)
V = c(9, 9, 9,3) 

findeev<-function(vi){ #takes a list of vector(s) to extract from `allv`
  nms=paste("v",vi,sep="")
  ne=max(sapply(allv[vi],length)) #max number of elements
  ine=1:ne
  # Computes sd along the positions of all vetors
  rest=apply(cbind(sapply(allv[vi],function(vt)vt[ine])),1,sd)
  # determine if some vectors have the same value across a position
  resc=which(rest==0)
  if(length(resc)){ret=allv[vi];ret$pos=resc
  names(ret)[-length(ret)]<-nms
  ret} else invisible()
}

allv=list(X,Y,Z,W,V)
findeev(c(3,5)) #exmple

sol=list();j=1 # This contains all pairs
for(i in (length(allv)-1):2){
  # compare all combinations of vector using `findeev`
  res<-apply(t(combn(1:length(allv),i )),1,findeev)
  if(is.null(res))next #not found continues
  # eliminate NAs form list and assign that to sol[[j]]
  sol[[j]]<-Filter(Negate(function(x) is.null(unlist(x))), res)
  j=j+1
}
sol

你得到:

> findeev(c(3,5))
$v3
[1] 8 8 9 6

$v5
[1] 9 9 9 3

$pos
[1] 3

> sol
[[1]]
[[1]][[1]]
[[1]][[1]]$v1
[1] 2 3 4

[[1]][[1]]$v2
[1] 4 3 5

[[1]][[1]]$v4
[1] 3 3 7 4

[[1]][[1]]$pos
[1] 2



[[2]]
[[2]][[1]]
[[2]][[1]]$v1
[1] 2 3 4

[[2]][[1]]$v2
[1] 4 3 5

[[2]][[1]]$pos
[1] 2


[[2]][[2]]
[[2]][[2]]$v1
[1] 2 3 4

[[2]][[2]]$v4
[1] 3 3 7 4

[[2]][[2]]$pos
[1] 2


[[2]][[3]]
[[2]][[3]]$v2
[1] 4 3 5

[[2]][[3]]$v4
[1] 3 3 7 4

[[2]][[3]]$pos
[1] 2


[[2]][[4]]
[[2]][[4]]$v3
[1] 8 8 9 6

[[2]][[4]]$v5
[1] 9 9 9 3

[[2]][[4]]$pos
[1] 3