R:R中的bfs()分别提取dist值

R: bfs() in R to extract dist values separately

我有一个邻接矩阵。

adjm <- matrix(sample(0:1, 100, replace=TRUE, prob=c(0.85,0.15)), nc=10)
for(i in 1:10)
{
for (j in 1:10) {
  if(i==j)
  { adjm[i,j]<-0 }
 } }
 colnames(adjm)<-c("A","B","C","D","E","F","G","H","I","J")

然后我将其转换为邻接关系 graph.Then 应用 bfs() 函数。因为我只需要距离和顶点,所以我只包含 "dist" 作为参数。

 g1 <- graph_from_adjacency_matrix( adjm )
 bfst<-bfs(g1, root=2, "all", dist=TRUE)

 $dist
 A B C D E F G H I J 
 0 2 1 3 1 1 2 2 1 2 

由此我可以将 dist 分开如下;

 bfst$dist
  A B C D E F G H I J 
  0 2 1 3 1 1 2 2 1 2 

为了访问这个 dist 独立组件,我使用了 bfst$dist[1]。但总是显示如下。

bfst$dist[1]
A
0

如果我想单独提取它们,我该怎么办。

是的,您可以访问没有名称的元素或没有名称的元素。但是,名称不会干扰操作。下面是一些示例:

vec <- 1:10
names(vec) <- LETTERS[1:10]
vec
#>  A  B  C  D  E  F  G  H  I  J 
#>  1  2  3  4  5  6  7  8  9 10

# we can access the names if we want
names(vec)
#>  [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J"

# or a name
names(vec)[1]
#> [1] "A"

# But the console output with both the name and
# the value is just a way of pretty-printing the
# result, it doesn't effect operations, e.g.
vec[1]
#> A 
#> 1
vec[1] * 10
#>  A 
#> 10

# however if you want to access an element
# without the name, use double brackets
vec[[1]]
#> [1] 1

# or to remove all names try
unname(vec)
#>  [1]  1  2  3  4  5  6  7  8  9 10