在R语言中,可以使用merge()
函数或者rbind()
函数来合并两个数据集。
merge()
函数合并两个数据集:# 创建两个数据集
df1 <- data.frame(ID = c(1, 2, 3, 4),
Name = c("John", "Amy", "Tom", "Linda"),
Age = c(25, 30, 35, 40))
df2 <- data.frame(ID = c(1, 2, 3, 4),
Gender = c("Male", "Female", "Male", "Female"),
Salary = c(5000, 6000, 7000, 8000))
# 使用merge()函数合并两个数据集
merged_df <- merge(df1, df2, by = "ID")
# 打印合并后的数据集
print(merged_df)
输出结果:
ID Name Age Gender Salary
1 1 John 25 Male 5000
2 2 Amy 30 Female 6000
3 3 Tom 35 Male 7000
4 4 Linda 40 Female 8000
rbind()
函数按行合并两个数据集:# 创建两个数据集
df1 <- data.frame(ID = c(1, 2, 3, 4),
Name = c("John", "Amy", "Tom", "Linda"),
Age = c(25, 30, 35, 40))
df2 <- data.frame(ID = c(5, 6, 7, 8),
Name = c("Mike", "Sara", "Jack", "Emily"),
Age = c(45, 50, 55, 60))
# 使用rbind()函数合并两个数据集
merged_df <- rbind(df1, df2)
# 打印合并后的数据集
print(merged_df)
输出结果:
ID Name Age
1 1 John 25
2 2 Amy 30
3 3 Tom 35
4 4 Linda 40
5 5 Mike 45
6 6 Sara 50
7 7 Jack 55
8 8 Emily 60
根据实际需求,选择适合的合并方式。