在 R 编程中将对象转换为数据帧 - as.data.frame()函数
R 编程语言中的as.data.frame()函数用于将对象转换为数据框。这些对象可以是向量、列表、矩阵和因子。
Syntax: as.data.frame(object)
Parameters:
- object: Vector, Matrix, factor, or data frame
R – as.data.frame()函数示例
示例 1:R 中 as.data.frame()函数的基本示例
R
# R program to convert object to data frame
# Creating Vectors
x1 <- c(1, 2, 3, 4)
x2 <- c("a", "B", "C", "D")
x3 <- c("hello", "Geeks", "for", "geeks")
# Creating list of vectors
x <- list(col1 = x1, col2 = x2, col2 = x3)
x
# Converting list to data frame
as.data.frame(x)
R
# R program to convert object to list
# Converting pre-defined dataset to list
x < - as.list(BOD)
x
# Converting list to data frame
as.data.frame(x)
输出:
$col1
[1] 1 2 3 4
$col2
[1] "a" "B" "C" "D"
$col2
[1] "hello" "Geeks" "for" "geeks"
col1 col2 col2.1
1 1 a hello
2 2 B Geeks
3 3 C for
4 4 D geeks
示例 2:
R
# R program to convert object to list
# Converting pre-defined dataset to list
x < - as.list(BOD)
x
# Converting list to data frame
as.data.frame(x)
输出:
$Time
[1] 1 2 3 4 5 7
$demand
[1] 8.3 10.3 19.0 16.0 15.6 19.8
attr(, "reference")
[1] "A1.4, p. 270"
Time demand
1 1 8.3
2 2 10.3
3 3 19.0
4 4 16.0
5 5 15.6
6 7 19.8