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

≡放荡痞女 提交于 2019-12-02 07:58:25

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 )
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!