Reputation: 171
I do have a problem that i just can't seem so solve.
Say I have a loop like the one provided by the minimal working example below. What I want R to do, is to create a new "summary" ( in this example "dogfood_items", "catfood_items", and "fishfood_items") variable for each iteration, i.e. I can't get the expression "summarize(str_c(food[i], "items", sep="_") = sum(items))" to work. Defining, an interim variable ( for example a <- str_c(food[i], "items", sep="_") ) and then writing summarize(a=sum(items) unfortunately also doesn't work.
What bugs me, is that "str_c(food[1], "items", "sep="_") standing on its own does work totally fine. It does not work within summarize(...).
Does anyone have an idea on how to get this working?
Please don't be to harsh on me. I'm pretty new to R.
Best wishes, David.
library(tidyverse)
food <- c("dogfood", "catfood", "fishfood")
output <- list()
data <- tribble(
~items, ~cost, ~staff, ~foodtype,
100, 200, 11, "dogfood",
120, 20, 12, "dogfood",
40, 120, 12, "catfood",
10, 12, 13, "fishfood",
)
data # view data
for (i in seq_along(food))
output[[i]] <- data %>%
filter(foodtype==food[i]) %>%
summarise(str_c(food[i], "items", sep="_")=sum(items)) # the problem is here !
Upvotes: 2
Views: 303
Reputation: 886938
If we want to name the columns on the lhs of assignment, use :=
and evaluate (!!
)
library(dplyr)
library(stringr)
output <- vector('list', length(food))
for (i in seq_along(food)) {
output[[i]] <- data %>%
filter(foodtype==food[i]) %>%
summarise(!! str_c(food[i], "items", sep="_") := sum(items))
}
output
#[[1]]
# A tibble: 1 x 1
# dogfood_items
# <dbl>
#1 220
#[[2]]
# A tibble: 1 x 1
# catfood_items
# <dbl>
#1 40
#[[3]]
# A tibble: 1 x 1
# fishfood_items
# <dbl>
#1 10
It may be easier to do a group by sum
operation
data %>%
group_by(foodtype) %>%
summarise(out = sum(items))
Upvotes: 1