Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R data frame columns from vector

Tags:

dataframe

r

I must be missing something obvious here but for this:

> range(data$timestamp)
[1] "2015-06-29 09:32:43.000 UTC" "2015-07-03 15:50:35.986 UTC"

I want to do something like:

df <- data.frame(as.Date(range(data$timestamp)))
names(df) <- c('from', 'to')

and get a data frame with columns 'from' and 'to' without needing an extra variable only to index. Written as above data.frame converts the vector to two rows in a single-column data frame. I've tried various combinations of cbind, matrix, t, list and attempts at destructuring. What is the best way to do this?

like image 692
Sam Brightman Avatar asked Nov 23 '25 11:11

Sam Brightman


1 Answers

df <- as.data.frame(as.list(as.Date(range(data$timestamp))))
names(df) <- c('from', 'to')

This will work. data.frames are really just special lists after all.

If you wanted a one-liner, you could use setNames. I've also found this type of thing much more readable now using magrittr:

data$timestamp %>% range %>% as.Date %>% as.list %>% as.data.frame %>% setNames(c("from", "to")

Alternatively, you could cast via a matrix:

df <- as.data.frame(matrix(as.Date(range(data$timestamp)), ncol = 2))
names(df) <- c('from', 'to')

This will, however, strip the class (and other attributes) from the dates. If you instead set the dimensions of the vector using dim<-, then neither print nor as.data.frame will treat it as a matrix (because it still has the class Date).

To get round this, convert to Date after creating the data.frame:

df <- as.data.frame(matrix(range(data$timestamp), ncol = 2))
df[] <- lapply(df, as.Date)
names(df) <- c('from', 'to')
like image 183
Nick Kennedy Avatar answered Nov 25 '25 03:11

Nick Kennedy