使用[[和向量]索引数据框时,日期列强制转换为数字

MrH*_*pko 10 r date dataframe purrr

我正在创建一个带有类型列的data.frame Date.[[使用数字向量索引数据框时,日期将变为数字.这在使用时会导致问题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
Run Code Online (Sandbox Code Playgroud)

Cri*_*uno 5

概观

在阅读为什么unlist()在R和文档中杀死日期之后unlist(),你必须手动防止purrr::map()通过使用该base::c()函数将Date对象强制转换为整数.

加载mikmart的PR版本 purrr::pmap()

在阅读了pmap strip之后Date,看起来有人非常棒的提交了一个pull请求来解决这个问题,该索引是在引擎盖下的重构版本中解决的purrr::pmap().

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

# ******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 #
Run Code Online (Sandbox Code Playgroud)