r - 使用[[和向量对数据框进行索引时,日期列将被强制转换为数字

标签 r date dataframe purrr

我正在创建一个数据类型为Date的列的data.frame。当使用[[和数字向量索引数据帧时,日期变为数字。使用purrr::pmap时,这会引起问题。谁能解释为什么会这样,有没有解决的办法?

例子:

x <- data.frame(d1 = lubridate::ymd(c("2018-01-01","2018-02-01")))

class(x$d1)
# [1] "Date"

x[[1]]
# [1] "2018-01-01" "2018-02-01"

x[[c(1, 1)]]
# [1] 17532

最佳答案

概述

阅读why does unlist() kill dates in R unlist() 的文档后,您必须使用 purrr::map() 函数手动阻止 base::c() 将Date对象强制转换为整数。

加载mikmart的PR版本的purrr::pmap()
阅读pmap strips Date 之后,看起来很厉害的submitted a pull request可以在 purrr::pmap() 幕后的重构索引版本中解决此问题。

使用 devtools::dev_mode() 可以安装mikmart/purrr purrr 's "pmap" branch版本,以在使用pmap()时保留Date对象。

# ******pmap() example ****
# load necessary packages -----
library(devtools)
library(lubridate)

# enter dev mode so you don't have to uninstall the cran version of purrr ----
dev_mode(on = TRUE)

# install mikmart's PR to fix the coercing of Dates to integer ----
install_github(repo = "mikmart/purrr", ref = "pmap")

# load mikmart's PR version of purrr ----
library(purrr)

# load necessary data
x <- data.frame(d1 = lubridate::ymd(c("2018-01-01","2018-02-01")))

# for the first column in x ----
# give me each element
# note: no need for c()
list.of.dates <-
  x %>%
  pmap(.f = ~ .x)

# view results -----
list.of.dates
# [[1]]
# [1] "2018-01-01"
# 
# [[2]]
# [1] "2018-02-01"

# view the class of each list -----
map_chr(list.of.dates, class) # [1] "Date" "Date"
#
# 
# turn off dev mode ---
dev_mode(on = FALSE)
#
# restart R -----
# Manually hit Shift+Cmd+F10 or point in click under the "Session" tab
#
# clear global environment ----
rm(list = ls())
#
# ******map() example********
# load necessary packages -----
library(tidyverse)
library(lubridate)

# load necessary data ----
x <- data.frame(d1 = lubridate::ymd(c("2018-01-01","2018-02-01")))

# from the first column ------
# give me each element
# and ensure the dates don't get coerced to integers
list.of.dates <-
  x$d1 %>%
  map(.f = ~ .x %>% c()) 

# view results -----
list.of.dates
# [[1]]
# [1] "2018-01-01"
# 
# [[2]]
# [1] "2018-02-01"

# # view the class of each list -----
map_chr(list.of.dates, class) # [1] "Date" "Date"

# end of script #

关于r - 使用[[和向量对数据框进行索引时,日期列将被强制转换为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52579980/

相关文章:

python - 使用 Pandas 中数据框的最后一列单独回归每一列

r - 使用Apply而不是for(使用数据框的2列)

r - 在 R 公式中,为什么我必须在幂项上使用 I() 函数,例如 y ~ I(x^3)

r - 在R编程中使用变量打印下一个闰年的值

sql - 在 PostgreSQL 中获取两个日期之间的结果

dataframe - Julia DataFrame 用 LOCF 填充 NA

r - ggplot2每一组仅包含一个观察值

mysql - 即使count=0 mysql也选择

Javascript getTime() 提供令人困惑的结果

python - 使用 pandas dataframe 进行多维计算