Calculate new value from another tibble

Hi Guys,

i´m a beginner in coding and use simple functions from the dplyr and tdyr packet. I generated the following tibble:

grafik

In the first column you see the calender week. In the second the option key 1,2,3 and 4. And in the third column yout see the frequency. Now i want to calculate 10 percent of option key 3 and substract that value from option key 3 and add that value to a third to option key 1,2 and 4. How can i best realize that? I tryed the following:

raw_disc <-
mutate(raw_count, Rabatt = Häufigkeit*0.1)

raw_part <-
mutate(raw_disc, Anteil = Rabatt/3)

raw_tastedrei <-
filter(raw_part, Tag == "taste 3")

raw_diff <-
mutate(raw_tastedrei, Anzahl = Häufigkeit - Anteil)

raw_add_tasteeins <-
filter(raw_part, Tag == "taste 1")

But now when i try to add up the value, in this case on option key 1, i get an error message.

mutate(raw_add_tasteeins, Anzahl = Häufigkeit + raw_add_tasteeins$Anteil)

:heavy_multiplication_x: Anzahl must be size 1, not 11.
:information_source: The error occurred in group 1: Kalenderwoche = 10.
Run rlang::last_error() to see where the error occurred.

Who can help me with this error and show me a better way to calculate that? Thanks a lot!


adf <- data.frame(
  week=rep(10:12,each=4),
  key=rep(paste0("t",1:4),3),
  someval = (1:12)^3 %% 50
)

#for each week :
#90% of key t3 + 33% of the other keys
library(tidyverse)

adf %>% 
  group_by(week) %>%
  summarise(
    val = sum(case_when(
                    key == 't3' ~ .9*someval,
                    TRUE        ~ someval/3)
  ))

Hi nirgrahamuk,

thank you a lot for your help. But when i run your code i get this here:

grafik

This is not exactly what i need. The final tibble/data.frame should be the same as in the tibbel above. But the only difference is that in the final tb/df the values should contain the propotion of 10 Percent.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.