如何在 R 数据框中将两列合并为一列?
在本文中,我们将讨论如何在 R 编程语言的数据框中将两列合并为一列。
方法一:使用 paste()函数
此函数用于使用分隔符连接数据框中的两列。
语法:
paste(data$column1, data$column2, sep=" ")
在哪里
- 数据是输入数据框
- column1 是第一列
- column2 to 是第二列
- sep 是要在两列之间分隔的分隔符
示例 1 :
R
# create dataframe
data = data.frame(firstname=c("akash", "kyathi", "preethi"),
lastname=c("deep", "lakshmi", "savithri"),
marks=c(89, 96, 89))
# display
print(data)
# combine first name and last name columns
# with blank separator
data$fullname = paste(data$firstname, data$lastname, sep=" ")
# display
data
R
# create dataframe
data = data.frame(firstname=c("akash", "kyathi", "preethi"),
lastname=c("deep", "lakshmi", "savithri"),
marks=c(89, 96, 89))
# display
print(data)
# combine first name and last name columns
# with blank separator
data$fullname = paste(data$firstname, data$lastname, sep="--")
# display
data
R
# import tidyr package
library(tidyr)
# create dataframe
data = data.frame(firstname=c("akash", "kyathi", "preethi"),
lastname=c("deep", "lakshmi", "savithri"),
marks=c(89, 96, 89))
# display
print(data)
# combine first name and last name columns
# with blank separator
data = unite(data, fullname, c(firstname, lastname))
# display
data
输出:
示例 2:
R
# create dataframe
data = data.frame(firstname=c("akash", "kyathi", "preethi"),
lastname=c("deep", "lakshmi", "savithri"),
marks=c(89, 96, 89))
# display
print(data)
# combine first name and last name columns
# with blank separator
data$fullname = paste(data$firstname, data$lastname, sep="--")
# display
data
输出:
方法二:使用 unite()函数
此函数在 tidyr 包中可用,我们必须加载该包并合并列。
语法:
unite(dataframe, combined_columnname, c(columns))
在哪里,
- 数据框是输入数据框
- columns 是要组合的数据框列
- combine_columnname 是组合列的名称
示例:
R
# import tidyr package
library(tidyr)
# create dataframe
data = data.frame(firstname=c("akash", "kyathi", "preethi"),
lastname=c("deep", "lakshmi", "savithri"),
marks=c(89, 96, 89))
# display
print(data)
# combine first name and last name columns
# with blank separator
data = unite(data, fullname, c(firstname, lastname))
# display
data
输出: