Learn R Programming

rstackdeque (version 1.1.1)

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

Description

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

Usage

"as.data.frame"(x, row.names = NULL, optional = FALSE, ...)

Arguments

x
rpqueue 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.

Value

a data.frame with the first row the previous front of the queue and last row the previous back.

Details

This function runs in $O(N)$ time in the size of the rpqueue, and will only work if all elements of the queue 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.rpqueue(x)), where as.list.rpqueue converts the rpqueue to a list where the front element becomes the first element of the list.

See Also

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

Examples

Run this code
q <- rpqueue()
q <- insert_back(q, data.frame(names = c("Bob", "Joe"), ages = c(25, 18)))
q <- insert_back(q, data.frame(names = c("Mary", "Kate", "Ashley"), ages = c(27, 26, 21)))
print(q)

qq <- as.data.frame(q)
print(qq)

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

qq <- as.data.frame(q)
print(qq)

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

Run the code above in your browser using DataLab