Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R : environment to data.frame

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

like image 950
Nicolas Rosewick Avatar asked Oct 20 '22 08:10

Nicolas Rosewick


1 Answers

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
like image 91
gagolews Avatar answered Nov 03 '22 07:11

gagolews