as.data.frame.rstack: Convert an rstack to a data.frame

Description Usage Arguments Details Value See Also Examples

View source: R/as.data.frame.rstack.R

Description

Converts the elements of an rstack into rows of a data.frame, if this is reasonable.

Usage

1
2
## S3 method for class 'rstack'
as.data.frame(x, row.names = NULL, optional = FALSE, ...)

Arguments

x

rstack to convert.

row.names

passed on to as.data.frame before final conversion.

optional

passed onto as.data.frame before final conversion.

...

passed onto as.data.frame before final conversion.

Details

This function runs in O(N) time in the size of the rstack, and will only work if all elements of the stack have the same length() (e.g., same number of columns), and if any of the elements have names, then those names do not conflict (e.g., same column names where used). This is accomplished by a call to do.call("rbind", as.list.rstack(x)), where as.list.rstack converts the rstack to a list where the top element becomes the first element of the list.

Value

a data.frame with the first row the previous top of the stack.

See Also

as.list.rstack for conversion to a list and the generic as.data.frame.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
s <- rstack()
s <- insert_top(s, data.frame(names = c("Bob", "Joe"), ages = c(25, 18)))
s <- insert_top(s, data.frame(names = c("Mary", "Kate", "Ashley"), ages = c(27, 26, 21)))
print(s)

sd <- as.data.frame(s)
print(sd)

## Elements may be similarly-named lists as well, representing individual rows:
s <- rstack()
s <- insert_top(s, list(name = "Bob", age = 25))
s <- insert_top(s, list(name = "Mary", age = 24))
print(s)

sd <- as.data.frame(s)
print(sd)

## Building a stack in a loop, converting to a dataframe after the fact:
s <- rstack()
for(i in 1:1000) {
 if(runif(1,0,1) < 0.5) {
   s <- insert_top(s, data.frame(i = i, type = "sqrt", val = sqrt(i)))
 } else {
   s <- insert_top(s, data.frame(i = i, type = "log", val = log(i)))
 }
 if(i %% 100 == 0) {
   print(i/1000)
 }
}
print(head(as.data.frame(s)))

rstackdeque documentation built on May 2, 2019, 4:15 a.m.