R 合并列,按值对齐,值不匹配时填充NA
这是非常困难的。我尝试了R 合并列,按值对齐,值不匹配时填充NA,r,R,这是非常困难的。我尝试了full\u join和bind\u cols和merge变体,但我无法完全实现这一点 我有: > (t1 <- data.frame(x = letters[10:3], stringsAsFactors = FALSE)) x 1 j 2 i 3 h 4 g 5 f 6 e 7 d 8 c 因此,它就像一个完全连接,但保留了两个列,并在存在差异的地方填充NAs。例如,这只给了我一列: > full_join(t1, t2, by = c("x"
full\u join
和bind\u cols
和merge
变体,但我无法完全实现这一点
我有:
> (t1 <- data.frame(x = letters[10:3], stringsAsFactors = FALSE))
x
1 j
2 i
3 h
4 g
5 f
6 e
7 d
8 c
因此,它就像一个完全连接
,但保留了两个列,并在存在差异的地方填充NAs。例如,这只给了我一列:
> full_join(t1, t2, by = c("x" = "y"))
x
1 j
2 i
3 h
4 g
5 f
6 e
7 d
8 c
9 a
10 b
虽然有点老套,但这是可行的:
full_join(
left_join(t1, t2 %>% mutate(x = y)),
left_join(t2, t1 %>% mutate(y = x))
)
x y
1 j <NA>
2 i <NA>
3 h <NA>
4 g <NA>
5 f <NA>
6 e <NA>
7 d d
8 c c
9 <NA> a
10 <NA> b
完全连接(
左联合(t1,t2%>%突变(x=y)),
左联合(t2,t1%>%突变(y=x))
)
xy
1 j
2我
3小时
4克
5楼
6 e
7天
8摄氏度
9 a
10 b
您还可以找到联合
和匹配
inds <- union(t1$x, t2$y)
data.frame(x = t1$x[match(inds, t1$x)], y = t2$y[match(inds, t2$y)])
# x y
#1 j <NA>
#2 i <NA>
#3 h <NA>
#4 g <NA>
#5 f <NA>
#6 e <NA>
#7 d d
#8 c c
#9 <NA> a
#10 <NA> b
inds
full_join(
left_join(t1, t2 %>% mutate(x = y)),
left_join(t2, t1 %>% mutate(y = x))
)
x y
1 j <NA>
2 i <NA>
3 h <NA>
4 g <NA>
5 f <NA>
6 e <NA>
7 d d
8 c c
9 <NA> a
10 <NA> b
inds <- union(t1$x, t2$y)
data.frame(x = t1$x[match(inds, t1$x)], y = t2$y[match(inds, t2$y)])
# x y
#1 j <NA>
#2 i <NA>
#3 h <NA>
#4 g <NA>
#5 f <NA>
#6 e <NA>
#7 d d
#8 c c
#9 <NA> a
#10 <NA> b