在R中的full_join中添加数据集标识符变量



当在R.中使用full_join()时,我想自动添加一个新的数据集标识符变量

df1 <- tribble(~ID, ~x,
"A", 1,
"B", 2,
"C", 3)
df2 <- tribble(~ID, ~y,
"D", 4,
"E", 5,
"F", 6)
combined <- df1 %>% dplyr::full_join(df2)

我从?full_join知道,它连接了df1后面的df2的所有行。但是,我找不到自动创建索引变量的选项。

目前,我正在df1第一个中添加一个额外的变量

df1 <- tribble(~ID, ~x, ~dataset,
"A", 1, 1,
"B", 2, 1,
"C", 3, 1)

并用df1 %>% dplyr::full_join(df2) %>% dplyr::mutate(dataset = replace_na(dataset, 2))跟踪

有什么建议可以用更好的方式来做吗?

我不确定它是否比你的效率更高,但如果除了id之外,总是不存在重叠列,那么你可以尝试

df1 %>%
full_join(df2) %>%
mutate(dataset = as.numeric(is.na(x))+1)
ID        x     y dataset
<chr> <dbl> <dbl>   <dbl>
1 A         1    NA       1
2 B         2    NA       1
3 C         3    NA       1
4 D        NA     4       2
5 E        NA     5       2
6 F        NA     6       2

但为了安全起见,最好事先定义它的索引。

df1 %>%
mutate(dataset = 1) %>%
full_join(df2 %>% mutate(dataset = 2))
ID        x     y dataset
<chr> <dbl> <dbl>   <dbl>
1 A         1    NA       1
2 B         2    NA       1
3 C         3    NA       1
4 D        NA     4       2
5 E        NA     5       2
6 F        NA     6       2

新数据

df1 <- tribble(~ID, ~x,~y,
"A", 1,1,
"B", 2,1,
"C", 3,1)
df2 <- tribble(~ID, ~x,~y,
"D", 4,1,
"E", 5,1,
"F", 6,1)
full_join(df1, df2)
ID        x     y
<chr> <dbl> <dbl>
1 A         1     1
2 B         2     1
3 C         3     1
4 D         4     1
5 E         5     1
6 F         6     1

而不是"加入";,可能尝试dplyr:中的bind_rows

library(dplyr)
bind_rows(df1, df2, .id = "dataset")

这将绑定行,并且用NA填充缺失的列。此外,您还可以指定一个";。id";带有标识符的参数。如果提供数据帧列表,则标签取自列表中的名称。如果不是,则使用数字序列(如下所示(。

输出

dataset ID        x     y
<chr>   <chr> <dbl> <dbl>
1 1       A         1    NA
2 1       B         2    NA
3 1       C         3    NA
4 2       D        NA     4
5 2       E        NA     5
6 2       F        NA     6

最新更新