将矩阵转换为 R 中的数据帧
在本文中,我们将讨论如何将矩阵转换为 DataFrame,或者我们也可以说我们将讨论如何在 R 编程语言中从矩阵创建一个 DataFrame。
可以使用名为as.data.frame()的函数将矩阵转换为数据帧。它将从矩阵中取出每一列并将其转换为数据框中的每一列。
语法:
as.data.frame(matrix_data)
其中,matrix_data 是输入矩阵。
示例 1:
R
# create the matrix with 4 rows
# with numeric elements
matrix_data=matrix(c(1,2,3,4,5,6,7,8),nrow=4)
# display the data
print(matrix_data)
# convert the matrix into dataframe
dataframe_data=as.data.frame(matrix_data)
# print dataframe data
print(dataframe_data)
R
# create the matrix with 8 rows
# with numeric elements
matrix_data=matrix(c(1,2,3,4,5,6,7,8,11:18),nrow=8)
# display the data
print(matrix_data)
# convert the matrix into dataframe
dataframe_data=as.data.frame(matrix_data)
# print dataframe data
print(dataframe_data)
R
# create the matrix with 8 rows
# with different elements
matrix_data=matrix(c(
"bobby","pinkey","rohith","gnanesh",5.3,6.6,7,8,11:18),nrow=8)
# display the data
print(matrix_data)
# convert the matrix into dataframe
dataframe_data=as.data.frame(matrix_data)
# print dataframe data
print(dataframe_data)
输出:
示例 2:
电阻
# create the matrix with 8 rows
# with numeric elements
matrix_data=matrix(c(1,2,3,4,5,6,7,8,11:18),nrow=8)
# display the data
print(matrix_data)
# convert the matrix into dataframe
dataframe_data=as.data.frame(matrix_data)
# print dataframe data
print(dataframe_data)
输出:
示例 3:
电阻
# create the matrix with 8 rows
# with different elements
matrix_data=matrix(c(
"bobby","pinkey","rohith","gnanesh",5.3,6.6,7,8,11:18),nrow=8)
# display the data
print(matrix_data)
# convert the matrix into dataframe
dataframe_data=as.data.frame(matrix_data)
# print dataframe data
print(dataframe_data)
输出: