我有一个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列中提取单个元素,那么我想在g1和g2列的所有元素的位置上添加两个额外的列。
l <- union(unique(g$g1), unique(g$g2))
[1] "Soil" "Feces" "Skin" "Tongue" "Freshwater" "Freshwater (creek)" "Ocean" "Mock" "Sediment (estuary)"因此,土壤在l中的位置对应于1,面向2,等等:
Soil : 1
Feces : 2
Skin : 3
Tongue : 4
Freshwater : 5
Freshwater (creek) : 6
Ocean : 7
Mock : 8
Sediment (estuary) : 9因此,我想在两个额外的柱中加上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我试过用list (l)和命令循环,但是我做不到
太感谢了
发布于 2021-04-19 19:00:09
溶液
library(tidyverse)
# creating a key
key <- structure(list(V1 = c("Soil", "Feces", "Skin", "Tongue", "Freshwater",
"Freshwater (creek)", "Ocean", "Mock", "Sediment (estuary)"),
V2 = c("1", "2", "3", "4", "5", "6", "7", "8", "9")), row.names = c(NA,
-9L), class = "data.frame")
df %>%
mutate(
xg1 = key$V2[match(df$g1, key$V1)],
xg2 = key$V2[match(df$g2, key$V1)]
)数据
df <- structure(list(g1 = c("Soil", "Soil", "Soil", "Soil", "Soil",
"Soil", "Feces", "Feces", "Feces", "Skin", "Tongue", "Freshwater",
"Freshwater (creek)", "Freshwater (creek)"), g2 = c("Feces",
"Skin", "Tongue", "Freshwater", "Ocean", "Mock", "Freshwater",
"Freshwater (creek)", "Sediment (estuary)", "Freshwater (creek)",
"Freshwater (creek)", "Freshwater (creek)", "Ocean", "Mock")), class = "data.frame", row.names = c(NA,
-14L))https://stackoverflow.com/questions/67167452
复制相似问题