我有两个数据帧。一个是仅包含名称的数据框
library(tidyverse)
df1 <- structure(list(name1 = c("B2m", "Itm2b", "Itm2b"), name2 = c("Cd44",
"Atp1b2", "Sppl2b")), row.names = c(NA, -3L), class = c("tbl_df",
"tbl", "data.frame"))
df1
# A tibble: 3 x 2
name1 name2
<chr> <chr>
1 B2m Cd44
2 Itm2b Atp1b2
3 Itm2b Sppl2b
另一个是存储上面所有名称的数据框:
df2 <- structure(list(name = structure(c(2L, 3L, 1L, 5L, 4L), .Label = c("Atp1b2",
"B2m", "Cd44", "Itm2b", "Sppl2b"), class = "factor")), row.names = c(NA,
-5L), class = c("tbl_df", "tbl", "data.frame"))
df2
# A tibble: 5 x 1
name
<fct>
1 B2m
2 Cd44
3 Atp1b2
4 Sppl2b
5 Itm2b
我想根据df1
中的行号将df2
转换为数字对,得出:
name1 name2
1 2
5 3
5 4
我如何方便地做到这一点?
答案 0 :(得分:3)
您可以使用:
sapply(df1, match, df2$name)
name1 name2
[1,] 1 2
[2,] 5 3
[3,] 5 4
或使用tidyverse进行相同操作:
library(purrr)
map_df(df1, match, df2$name)
# A tibble: 3 x 2
name1 name2
<int> <int>
1 1 2
2 5 3
3 5 4