因此对于我目前正在从事的项目,我有一个数字数据框(称为A)。 data.frame A由1个变量和300000行不同的数字组成。
除了A之外,我还有data.frame B和C。数据frame B和C都具有315个变量,并且共享相同的结构(具有相同的数据类型,但值/变量名称不同)。
A,B和C都共享相同的第一个变量,这是它们的主键。 A包含整个数字列表,而B和C都包含该列表的子集。
我想做的是将B和C中第一个变量的数字与A中的数字匹配,如果它们匹配,那么B和C中所有相关行的所有数据都应放入A中。
在SQL中,我知道您可以更新表并根据匹配的结果添加行。但是,不允许在此分配中使用任何SQL命令(因此我无法使用sqldf库),而且我不知道如何在R中执行此操作。
举例来说,假设您具有以下带有信息的数据框:
A。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var barChartData = {
labels: ['6/30', '7/31', '8/31'],
datasets: [
{
label: false,
data: [0, 10, 20, 30, 40, 50, 60, 70, 80],
fill: false,
borderColor: '#EC932F',
backgroundColor: '#EC932F',
pointBorderColor: '#EC932F',
pointBackgroundColor: '#EC932F',
pointHoverBackgroundColor: '#EC932F',
pointHoverBorderColor: '#EC932F',
yAxisID: 'y-axis-2'
},
{
type: 'line',
label: 'line',
borderColor:'red',
borderWidth: 2,
fill: false,
data: [73.6, 72.0, 71.0],
yAxisID: 'y-axis-2'
},
{
type: 'bar',
label: 'Dataset 2',
backgroundColor:'blue',
data: [1328, 1380, 1380],
borderColor: 'white',
borderWidth: 2
}, {
type: 'bar',
label: 'Dataset 3',
backgroundColor: 'yellow',
data: [978, 993, 980],
},
{
label: false,
data: [0,500,1000,1500,2000,2500,3000],
fill: false,
yAxisID: 'y-axis-1'
},
]
};
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js Combo Bar Line Chart'
},
tooltips: {
mode: 'label',
intersect: true
},
elements: {
line: {
fill: false,
},
},
scales: {
xAxes: [{
display: true,
gridLines: {
display: false
},
labels: {
show: true,
}
}],
yAxes: [
{
type: "linear",
display: true,
position: "left",
id: "y-axis-1",
gridLines:{
display: false
},
labels: {
show:true,
}
},
{
type: "linear",
display: true,
position: "right",
id: "y-axis-2",
gridLines:{
display: false
},
labels: {
show:true,
}
}
]
}
}
});
};
</script>
</body>
</html>
B。
KEY
1
2
3
4
5
6
7
C。
B_KEY VAR_B_2 VAR_B_3
2 AB 134
4 AC 135
7 AD 136
这应该导致:
A。
C_KEY VAR_C_2 VAR_C_3
2 BD 250
3 BE 251
5 BF 252
7 BG 253
答案 0 :(得分:0)
我们可以使用嵌套的merge
merge(merge(A, B, by.x = "KEY", by.y = "B_KEY", all.x = TRUE), C,
by.x = "KEY", by.y = "C_KEY", all.x = TRUE)
但是,如果我们在所有数据帧中都将“ KEY”列的列名保持不变,则使用Reduce
会变得更简单,更短
names(B)[1] <- "KEY"
names(C)[1] <- "KEY"
Reduce(function(x, y) merge(x, y, all.x = TRUE), list(A, B, C))
# KEY VAR_B_2 VAR_B_3 VAR_C_2 VAR_C_3
#1 1 <NA> NA <NA> NA
#2 2 AB 134 BD 250
#3 3 <NA> NA BE 251
#4 4 AC 135 <NA> NA
#5 5 <NA> NA BF 252
#6 6 <NA> NA <NA> NA
#7 7 AD 136 BG 253