简体   繁体   中英

Result type for group 1`` Error when using factor in dplyr mutate

The following code throws me an error:

dfTest <- structure(list(Year = c(2018, 2018, 2018, 2018, 2018, 2018, 2018, 
                        2018, 2018, 2018, 2018, 2019, 2019, 2019, 2019, 2019, 2019, 2019, 
                        2019, 2019, 2019, 2019, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 
                        2020, 2020, 2020, 2020, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 
                        2021, 2021, 2021, 2021)),
          class = c("grouped_df", "tbl_df", "tbl", "data.frame"),
          row.names = c(NA, -44L),
          groups = structure(list(
            Year = c(2018, 2019, 2020, 2021), 
            .rows = structure(list( 1:11, 12:22, 23:33, 34:44),
                              ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr", "list"))),
            class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -4L), .drop = TRUE))

dfTest %>% mutate(Year = factor(Year, ordered = T))

The error is

Error in `mutate()`:
! Problem while computing `Year = factor(Year, ordered = T)`.
Caused by error:
! `Year` must return compatible vectors across groups.
ℹ Result type for group 1 (Year = 2018): <ordered<a0764>>.
ℹ Result type for group 2 (Year = 2019): <ordered<4e60d>>.
Run `rlang::last_error()` to see where the error occurred.

I did not find immediately the answer on the web, so I thought it might be of some interest for the community.

The problem here seems that trying to use the factor function on a grouped variable causes an error. Simply adding an ungroup step solves the problem:

dfTest <- structure(list(Year = c(2018, 2018, 2018, 2018, 2018, 2018, 2018, 
                        2018, 2018, 2018, 2018, 2019, 2019, 2019, 2019, 2019, 2019, 2019, 
                        2019, 2019, 2019, 2019, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 
                        2020, 2020, 2020, 2020, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 
                        2021, 2021, 2021, 2021)),
          class = c("grouped_df", "tbl_df", "tbl", "data.frame"),
          row.names = c(NA, -44L),
          groups = structure(list(
            Year = c(2018, 2019, 2020, 2021), 
            .rows = structure(list( 1:11, 12:22, 23:33, 34:44),
                              ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr", "list"))),
            class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -4L), .drop = TRUE))

dfTest %>%
ungroup %>%
mutate(Year = factor(Year, ordered = T))

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