Group (factorial) data with multiple factors. error: incompatible size (0), expecting 1 (the group size) or 1

前端 未结 1 721
长发绾君心
长发绾君心 2021-01-24 03:52

This post is a following up of Changing line color in ggplot based on "several factors" slope

I would like to group the data (bellow) by \"PQ\", however I get

1条回答
  •  梦谈多话
    2021-01-24 04:18

    The error is due to the difference in length from the output of diff with respect to the original dataset. It returns one element less than the original data. So appending a 0 or NA will solve the issue

    df %>% 
       filter(N=="N0" | N=="N1") %>%
       group_by(PQ) %>% 
       mutate(slope = c(0, diff(Value)))
    

    To make it compact, instead of ==, we can use %in% when there are multiple elements

    df %>%
       filter(N %in%  paste0("N", 0:1)) %>%
       group_by(PQ) %>%
       mutate(slope = c(0, diff(Value)))
    

    Regarding the second issue, about doing this for all the combinations in 'N', use the combn on the unique elements of 'N', filter the 'N' based on the combination values, after grouping by 'PQ', calculate the diff of 'Value'. The output will be a list as we specified simplify = FALSE.

    combn(as.character(unique(df$N)),2, FUN = function(x) df %>% 
                filter(N %in% x) %>% 
                group_by(PQ) %>%
                mutate(slope = c(0, diff(Value))), simplify = FALSE )
    

    0 讨论(0)
提交回复
热议问题