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).
(在igraph
, tidygraph
等中,您还保留了第二个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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…