R 向现有数据框中添加行数较少的 df 并显示 NA [英] R adding a df with less rows to an existing data frame and show NA
问题描述
我有一个数据框,比如说 df1,它看起来像这样:
I have a data frame, say df1, that looks something like this:
ID
1 ABC
2 ABD
3 ABE
4 ABF
5 ABG
.
.
并且我想将一个数据框加入到 df1 中,该数据框的行数少于 df1,如下所示:
and I want to join a data frame to df1 that has less rows than df1, like this one:
ID Value1 Value 2
1 ABC 5 6
2 ABD 1 2
3 ABG 4 4
.
.
使最终产品看起来像这样:
so that the final product looks like this:
ID Value1 Value 2
1 ABC 5 6
2 ABD 1 2
3 ABE NA NA
4 ABF NA NA
5 ABG 4 4
.
.
我该怎么做?提前致谢.
How can I do about doing this? Thanks in advance.
推荐答案
数据
df1 = data.frame(ID = c("ABC", "ABD", "ABE", "ABF", "ABG"))
df2 = data.frame(ID = c("ABC", "ABD", "ABG"), Value1 = c(5, 4, 1), Value2 = c(6, 2, 4))
解决方案
merge(df1, df2, all.x = TRUE)
# ID Value1 Value2
#1 ABC 5 6
#2 ABD 4 2
#3 ABE NA NA
#4 ABF NA NA
#5 ABG 1 4
说明
阅读 ?merge
,我们看到逻辑参数 all.x
完全符合您的要求:
Explanation
Reading ?merge
, we see that the logical argument all.x
does exactly what you wanted:
all.x
逻辑;如果为 TRUE,则额外的行将被添加到输出中,一为x 中在 y 中没有匹配行的每一行.这些行将有 NA在那些通常用来自 y 的值填充的列中.这默认值为 FALSE,因此只有包含来自 x 和 y 的数据的行才是包含在输出中.
logical; if TRUE, then extra rows will be added to the output, one for each row in x that has no matching row in y. These rows will have NAs in those columns that are usually filled with values from y. The default is FALSE, so that only rows with data from both x and y are included in the output.
这篇关于R 向现有数据框中添加行数较少的 df 并显示 NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!