【发布时间】:2021-04-19 18:27:27
【问题描述】:
我有一个包含 2 列的数据框
groups
g1 g2
1 Soil Feces
2 Soil Skin
3 Soil Tongue
4 Soil Freshwater
6 Soil Ocean
8 Soil Mock
11 Feces Freshwater
12 Feces Freshwater (creek)
14 Feces Sediment (estuary)
18 Skin Freshwater (creek)
23 Tongue Freshwater (creek)
27 Freshwater Freshwater (creek)
31 Freshwater (creek) Ocean
33 Freshwater (creek) Mock
所以我想根据 g1 和 g2 列的所有元素的位置添加 2 个额外的列,如果我们根据 g1 和 g2 列提取单个元素
l <- union(unique(g$g1), unique(g$g2))
[1] "Soil" "Feces" "Skin" "Tongue" "Freshwater" "Freshwater (creek)" "Ocean" "Mock" "Sediment (estuary)"
所以l中Soil的位置对应1,Faces对应2,以此类推:
Soil : 1
Feces : 2
Skin : 3
Tongue : 4
Freshwater : 5
Freshwater (creek) : 6
Ocean : 7
Mock : 8
Sediment (estuary) : 9
所以我想在 2 个额外的列中添加 g1 和 g2 中的位置基数,如果土壤对应于 1,粪便对应于 2,那么 xg1 和 xg2 将对应于 1 和 2,类似于:
groups
g1 g2 xg1 xg2
1 Soil Feces 1 2
2 Soil Skin 1 3
3 Soil Tongue 1 4
4 Soil Freshwater 1 5
6 Soil Ocean 1 7
8 Soil Mock 1 8
11 Feces Freshwater 2 5
12 Feces Freshwater (creek) 2 6
14 Feces Sediment (estuary) 2 9
18 Skin Freshwater (creek) 3 6
23 Tongue Freshwater (creek) 4 6
27 Freshwater Freshwater (creek) 5 6
31 Freshwater (creek) Ocean 6 7
33 Freshwater (creek) Mock 6 8
我已经尝试使用列表 (l) 和命令进行循环,但我无法做到
非常感谢
【问题讨论】: