Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

r - 如何在不使用as_tbl_graph()的情况下创建相同的结果?(how can I create identical result without using as_tbl_graph()?)

My dataframe looks like this.

(我的数据框看起来像这样。)

Word1    Word2    Count
--------------------------
 a         b        4

 c         a        2

 b         c        1
-------------------------

I want the following result.

(我想要以下结果。)

from      to    count
-----------------------
  1       3       4

  2       1       2

  3       2       1

----------------------

I know I can achieve this easily using as_tbl_graph(df).

(我知道我可以使用as_tbl_graph(df)轻松实现这一目标。)

But I want this result only using base r code without using other packages.

(但是我只希望使用base r代码而不使用其他软件包来获得此结果。)

How can I create identical result without using other packages such as igraph, ggraph, tidyverse ...?

(如何在不使用igraph,ggraph,tidyverse等其他软件包的情况下创建相同的结果?)

  ask by jjw translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can convert the values to factor and then integer to accomplish that:

(您可以将值转换为factor然后再整数以完成此操作:)

lvls <- unique(df$Word1)                    # first we create an object containing the levels found in Word1

df$Word1 <- factor(df$Word1, levels = lvls) # Using this we convert both columns to factor
df$Word2 <- factor(df$Word2, levels = lvls)

df$Word1 <- as.integer(df$Word1)            # When converting this to integer, only level IDs are kept
df$Word2 <- as.integer(df$Word2)

df
#>   Word1 Word2 Count
#> 1     1     3     4
#> 2     2     1     2
#> 3     3     2     1

In igraph , tidygraph etc you also keep a second data.frame which consists of the level names (ie, the node description).

(在igraphtidygraph等中,您还保留了第二个data.frame ,它由级别名称(即节点描述)组成。)

We can create this from the levels saved before:

(我们可以从之前保存的级别中创建:)

df_nodes <- data.frame(names = lvls, stringsAsFactors = FALSE)
df_nodes
#>   names
#> 1     a
#> 2     c
#> 3     b

data (数据)

df <- read.csv(text = "Word1,Word2,Count
a,b,4
c,a,2
b,c,1", stringsAsFactors = FALSE)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...