如何合并不同长度的 R DataFrames?
在本文中,我们将讨论如何在 R 编程语言中组合两个不同长度的数据帧并制作一个最终的数据帧。
脚步 -
- 创建第一个数据框
- 创建第二个数据框
- 使用下面给出的任何函数并将它们组合起来
- 显示这样创建的数据集
方法一:使用合并函数
R 有一个名为 merge 的内置函数,它自动组合两个不同长度的数据帧。
句法:
merge(dataframe1, dataframe 2)
例子:
R
# 1st Dataframe
emp.data <- data.frame(
emp_id = c (1:5),
emp_name = c("Ryan","Sita","Ram","Raj","Gargi"),
salary = c(62.3,151,311.0,429.0,822.25)
)
# 2nd Dataframe
df2 <- data.frame(
height = c ("5'3","5'11","4'9","6"),
weight = c(55.8,68,89,42.9)
)
merge(emp.data, df2)
R
# 1st Dataframe
emp.data <- data.frame(
emp_id = c (1:5),
emp_name = c("Ryan","Sita","Ram","Raj","Gargi"),
salary = c(62.3,151,311.0,429.0,822.25)
)
# 2nd Dataframe
df2 <- data.frame(
height = c ("5'3","5'11","4'9","6"),
weight = c(55.8,68,89,42.9)
)
# creating the column id for dataframe 1
emp.data = cbind("id"=rownames(emp.data),emp.data)
# creating column id for dataframe 2
df2 = cbind("id"=rownames(df2),df2)
merge(emp.data,df2,all=T)
输出:
emp_id emp_name salary height weight
1 1 Ryan 62.30 5’3 55.8
2 2 Sita 151.00 5’3 55.8
3 3 Ram 311.00 5’3 55.8
4 4 Raj 429.00 5’3 55.8
5 5 Gargi 822.25 5’3 55.8
6 1 Ryan 62.30 5’11 68.0
7 2 Sita 151.00 5’11 68.0
8 3 Ram 311.00 5’11 68.0
9 4 Raj 429.00 5’11 68.0
10 5 Gargi 822.25 5’11 68.0
11 1 Ryan 62.30 4’9 89.0
12 2 Sita 151.00 4’9 89.0
13 3 Ram 311.00 4’9 89.0
14 4 Raj 429.00 4’9 89.0
15 5 Gargi 822.25 4’9 89.0
16 1 Ryan 62.30 6 42.9
17 2 Sita 151.00 6 42.9
18 3 Ram 311.00 6 42.9
19 4 Raj 429.00 6 42.9
20 5 Gargi 822.25 6 42.9
方法二:使用cbind
在此,我们将为两个数据帧创建一个名为 id 的列,并按列 id 组合数据帧。
Syntax: cbind(x1, x2, …, deparse.level = 1)
Parameters:
- x1, x2: vector, matrix, data frames
- deparse.level: This value determines how the column names generated. The default value of deparse.level is 1.
例子:
电阻
# 1st Dataframe
emp.data <- data.frame(
emp_id = c (1:5),
emp_name = c("Ryan","Sita","Ram","Raj","Gargi"),
salary = c(62.3,151,311.0,429.0,822.25)
)
# 2nd Dataframe
df2 <- data.frame(
height = c ("5'3","5'11","4'9","6"),
weight = c(55.8,68,89,42.9)
)
# creating the column id for dataframe 1
emp.data = cbind("id"=rownames(emp.data),emp.data)
# creating column id for dataframe 2
df2 = cbind("id"=rownames(df2),df2)
merge(emp.data,df2,all=T)
输出 :
id emp_id emp_name salary height weight
1 1 Ryan 62.30 5’3 55.8
2 2 Sita 151.00 5’11 68.0
3 3 Ram 311.00 4’9 89.0
4 4 Raj 429.00 6 42.9
5 5 Gargi 822.25