I have groups of 20 where only one observation has the value of one on a variable and I am trying to transform the other variables so that the remaining 19 observations and I am getting the following error.
"longer object length is not a multiple of shorter object length"
library(dplyr)
test <- data.frame('prod_id'= c("shoe", "shoe", "shoe", "shoe", "shoe",
"shoe", "boat", "boat","boat","boat","boat","boat", "ship", "ship", "ship",
"ship", "ship", "ship"),
'seller_id'= c("a", "b", "c", "d", "e", "f", "a","g", "h", "r",
"q", "b", "qe", "dj", "d3", "kk", "dn", "de"),
'Dich'= c(1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0),
'price' = c(120, 20, 10, 4, 3, 4, 30, 43, 56, 88, 75, 44, 32,
21, 44, 54, 55, 33)
)
Interestingly this code works:
test2 <- test %>%
group_by(prod_id) %>%
mutate(price_diff = if(any(Dich ==1)) ((price - price[Dich ==
1])/(price + price[Dich == 1])/2) else NA)
While this code
test2 <- test %>%
group_by(prod_id) %>%
mutate(diff_p = if(any(Dich==1)) price - price[Dich == 1] else NA)
is giving me the "longer object length is not a multiple of shorter object length" error. Unfortunately I wasn't able to reproduce in the example data so I'm hoping someone can see what the issue is.
I saw this post
Longer object length is not a multiple of shorter object length?
but the objects are both the same number of rows and I'm not sure why the one syntax would work while just slightly changing the transformation give me the error.