📜  如何合并不同长度的 R DataFrames?

📅  最后修改于: 2022-05-13 01:55:27.875000             🧑  作者: Mango

如何合并不同长度的 R DataFrames?

在本文中,我们将讨论如何在 R 编程语言中组合两个不同长度的数据帧并制作一个最终的数据帧。

脚步 -

  • 创建第一个数据框
  • 创建第二个数据框
  • 使用下面给出的任何函数并将它们组合起来
  • 显示这样创建的数据集

方法一:使用合并函数

R 有一个名为 merge 的内置函数,它自动组合两个不同长度的数据帧。

句法:

例子:



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)



输出:

方法二:使用cbind

在此,我们将为两个数据帧创建一个名为 id 的列,并按列 id 组合数据帧。

例子:

电阻

# 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)




输出 :