在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
根據實際需求,選擇適合的合并方式。