简体   繁体   中英

stack is failing on date vectors

Just came across a little peculiarity (for myself), and it took me a while to understand the problem. Thus here for future reference

When using stack on a named vector of Date (or POSIX) class, it fails:

vec_works <- setNames(letters, LETTERS)

head(stack(vec_works))
#>   values ind
#> 1      a   A
#> 2      b   B
#> 3      c   C
#> 4      d   D
#> 5      e   E
#> 6      f   F

vec_fail <- as.Date(ISOdate(1, 1, 1:7))
names(vec_fail) <- weekdays(vec_fail)
stack(vec_fail)
#> Error in stack.default(vec_fail): at least one vector element is required

The reason is that stack works on vectors that are actually vectors (!).

?stack

Note that stack applies to vectors (as determined by is.vector): non-vector columns (eg, factors) will be ignored with a warning.

is.vector(vec_fail)
#> [1] FALSE

It is still somewhat mind-blowing to me that lists are vectors, but data frames and factors are not ... !

is.vector(list())
#> [1] TRUE

is.vector(factor())
#> [1] FALSE

is.vector(data.frame())
#> [1] FALSE

luckily, there are other ways to solve the above problem, as suggested in this thread

Eg, tibble::enframe works very well:

tibble::enframe(vec_fail)
#> # A tibble: 7 × 2
#>   name      value     
#>   <chr>     <date>    
#> 1 Monday    0001-01-01
#> 2 Tuesday   0001-01-02
#> 3 Wednesday 0001-01-03
#> 4 Thursday  0001-01-04
#> 5 Friday    0001-01-05
#> 6 Saturday  0001-01-06
#> 7 Sunday    0001-01-07

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