Reputation: 12077
I am trying to understand why rbind.data.frame
converts my dates to numeric format and how do I fix it. Suppose I have the following:
v <- list(
row1=list(col1 = as.Date("2011-01-23"), col2="A"),
row2=list(col1 = as.Date("2012-03-03"), col2="B"))
Now I try to do:
df <- do.call(rbind.data.frame, v)
str(df)
'data.frame': 2 obs. of 2 variables:
$ col1: num 14997 15402
$ col2: Factor w/ 2 levels "A","B": 1 2
Why did col1
become a num? How do I fix it so it properly becomes a Date
field in df
.
NOTE: I would prefer a native R solution but other packages would be interesting to see
Upvotes: 5
Views: 1833
Reputation: 25854
Building on 42-'s comment Rather than using list in the "inner" level of construction, use data.frame, for this example, you can convert the inner list to a data.frame
, and then rbind
works as expected.
> d = do.call(rbind, lapply(v, as.data.frame))
> str(d)
'data.frame': 2 obs. of 2 variables:
$ col1: Date, format: "2011-01-23" "2012-03-03"
$ col2: Factor w/ 2 levels "A","B": 1 2
Upvotes: 3
Reputation: 3183
Use dplyr
> library(dplyr)
> df <- bind_rows(v)
> df
# A tibble: 2 x 2
col1 col2
<date> <chr>
1 2011-01-23 A
2 2012-03-03 B
Upvotes: 3