0
beer <- c("1"="BUD LIGHT","2"="BUSCH LIGHT","3"="COORS LIGHT","4"='MILLER LITE',"5"="NATURAL LIGHT")

for (i in 1:5) {
  df2 <- beer_markets
  df2 <- df2 %>% group_by(hh)
  df2 <- df2 %>% summarise(
    "BUD LIGHT" = sum(brand == "BUD LIGHT"),
  )
  df <- mutate(df, "BUD LIGHT" = df2$"BUD LIGHT")
}

`

Basically i want to replace every instance of "BUD LIGHT" inside of the loop with the dictionary value of beer[i] so that i can mutate through all 5 of the variables with just one loop

I tried

beer <- c("1"="BUD LIGHT","2"="BUSCH LIGHT","3"="COORS LIGHT","4"='MILLER LITE',"5"="NATURAL LIGHT")

for (i in 1:5) {
df2 <- beer_markets
df2 <- df2 %\>% group_by(hh)
df2 <- df2 %\>% summarise(
beer[i]  b = sum(brand == beer[i]),
)
df <- mutate(df, beer[i] = df2$beer[i])
}

I was expecting it to use the value of beer[i] but it ended in error

  • I'd recommend Ben Bolker's answer at the (first) marked duplicate. It's the right mix of easy and current. Mr Flick's answer at the second duplicate is also very good. – Gregor Thomas Oct 26 '22 at 03:48
  • Generally though, I doubt you need to loop like this at all. It's hard to tell exactly what you're doing wihtout seeing a sample of `beer_markets`, but I bet this could all be done another way. Something like `beer_markets %>% count(hh, beer) %>% tidyr::pivot_wider(names_from = beer, values_from = n)`. – Gregor Thomas Oct 26 '22 at 03:54
  • Gregor Thomas You found exactly what I needed, that second one from Mr Flick worked perfectly! Thank You! – Gregistopal Oct 26 '22 at 04:50

0 Answers0