I've an environment object in R and I want convert it to a data.frame. I tried as.data.frame but it didn't accept environment object.. Anyone has an idea ?
e <- new.env(hash=TRUE,size=3)
assign(x="a",value=10,envir=e)
assign(x="b",value=100,envir=e)
assign(x="c",value=1000,envir=e)
Thanks
Perform an intermediate step by converting an environment object to a list:
as.data.frame(as.list(e))
## c a b
## 1 1000 10 100
BTW: In fact, each data frame is represented by a list (consisting of atomic vectors of the same lengths) with a row.names
attribute set:
x <- data.frame(v1=1:2, v2=c("a", "b"))
unclass(x)
## $v1
## [1] 1 2
##
## $v2
## [1] a b
## Levels: a b
##
## attr(,"row.names")
## [1] 1 2
typeof(x)
## [1] "list"
mode(x)
## [1] "list"
is.list(x)
## [1] TRUE
And conversely:
x <- list(v1=1:2, v2=c("a", "b"))
attr(x, 'row.names') <- as.character(1:2)
class(x) <- 'data.frame'
print(x)
## v1 v2
## 1 1 a
## 2 2 b
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With