简体   繁体   中英

Using tidyverse %>% pipe with Dates and format(); how to prevent gobbledygook characters?

I have a tibble with a column formatted as Dates. For the purposes of the question, I'll generate similar data (the real data is much larger!):

> dates = tribble(~YrMon, "2011-01-01", "2011-02-01", "2011-03-01", "2011-04-01") 
              %>% mutate(YrMon = as.Date(YrMon))
> dates
# A tibble: 4 x 1
  YrMon     
  <date>    
1 2011-01-01
2 2011-02-01
3 2011-03-01
4 2011-04-01

I want to isolate just the months. When I extract the months without using a pipe it works as expected:

> format(dates$YrMon, "%m")
[1] "01" "02" "03" "04"

However, when I use a tidyverse pipe to do what I think should be the same thing, I get gobbledygook (I assume this is some sort of formatting of the tibble being returned):

> dates %>% format(.$YrMon, "%m")
[1] "\033[38;5;246m# A tibble: 4 x 1\033[39m"          
[2] "  YrMon     "                                     
[3] "  \033[3m\033[38;5;246m<date>\033[39m\033[23m    "
[4] "\033[38;5;250m1\033[39m 2011-01-01"               
[5] "\033[38;5;250m2\033[39m 2011-02-01"               
[6] "\033[38;5;250m3\033[39m 2011-03-01"               
[7] "\033[38;5;250m4\033[39m 2011-04-01"

What's going on and is there a way to get the expected answers using a %>% pipe?

You don't want dot automatically inserted so use this:

dates %>% { format(.$YrMon, "%m") }
## [1] "01" "02" "03" "04"

or use the magrittr %$% pipe:

library(magrittr)
dates %$% format(YrMon, "%m")
## [1] "01" "02" "03" "04"

This would also work:

dates %>% with(format(YrMon, "%m"))
## [1] "01" "02" "03" "04"

You can achieve the desired output in a couple of ways. We can use pull to extract our target column and deal with that as follows:

dates %>% pull(YrMon) %>% format(., "%m")
[1] "01" "02" "03" "04"

Alternatively, we can simply use mutate as follows:

dates %>% 
 mutate(YrMon = format(YrMon, "%m"))
# A tibble: 4 x 1
  YrMon
  <chr>
1 01   
2 02   
3 03   
4 04 

One can also get the month with lubridate 's month (returns an integer):

dates %>% 
   mutate(YrMon = month(YrMon))
# A tibble: 4 x 1
  YrMon
  <int>
1     1
2     2
3     3
4     4

With map (gives us a list, use map_* to override):

dates %>% 
   map(.,format,"%m")
$YrMon
[1] "01" "02" "03" "04"

Without using the pipe, one can simply do:

with(dates, format(YrMon, "%m"))
[1] "01" "02" "03" "04"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM