Anonymous
Anonymous

Reputation: 3

R for loop results

I need to store the results of my loop in a data frame but i can't figure it out. I got the loop working as shown below.

Pasta_pesto <- list(ingredienten = c("spaghetti","basilicum","pijnboompitten","pesto"))
Broccoli_spinaziesoep <- list(ingredienten = c("broccoli", "spinazie"))
Romige_kipcurry <- list(ingredienten = c("zilvervliesrijst", "sperziebonen", "kip", "curry"))

recepten <- list(Pasta_pesto, Broccoli_spinaziesoep, Romige_kipcurry)

food_box <- list("spaghetti", "pesto", "kip", "curry")

for (i in recepten) {
   for (e in i) {
      for (j in e) {
          for (k in food_box) {
            if (k == j){
            print(c("true", j, k))
          }
            else {
            print(c("false", j, k))}}}}}

rights now its prints out true or false but the end result should be a table with the following columns: recepten, count of true per recept, total items in recept list. as you can see the amount of true's have to be count and stored.

I hope any of you can help me.

Upvotes: 0

Views: 109

Answers (3)

Bruno
Bruno

Reputation: 4151

There was a bug when no words were found fixed it

library(tidyverse)

Pasta_pesto <- list(Pasta_pesto = c("spaghetti","basilicum","pijnboompitten","pesto"))
Broccoli_spinaziesoep <- list(Broccoli_spinaziesoep = c("broccoli", "spinazie"))
Romige_kipcurry <- list(Romige_kipcurry = c("zilvervliesrijst", "sperziebonen", "kip", "curry"))

recepten <- list(Pasta_pesto, Broccoli_spinaziesoep, Romige_kipcurry)

food_box<- list("spaghetti", "pesto", "kip", "curry", "basilicum", "pijnboompitten")

operation <- function(x,y){
  count_ingredients <- length(x)
  ingredient_in_food_box  <- x %in% y
  count_of_true <-  ingredient_in_food_box %>% sum
  missing_ingredients <- x[!ingredient_in_food_box] %>% str_flatten(collapse = "_") %>% list
  list(count_ingredients = count_ingredients,
       count_of_true = count_of_true,
       which_ingredient =  missing_ingredients)

}

recepten %>%
  flatten() %>% 
  map_dfr(~ operation(.,food_box),.id = "receipen") %>% 
  mutate(show = which_ingredient %>% as.character())
#> # A tibble: 3 x 5
#>   receipen       count_ingredien… count_of_true which_ingredient show           
#>   <chr>                     <int>         <int> <list>           <chr>          
#> 1 Pasta_pesto                   4             4 <chr [0]>        character(0)   
#> 2 Broccoli_spin…                2             0 <chr [1]>        broccoli_spina…
#> 3 Romige_kipcur…                4             2 <chr [1]>        zilvervliesrij…

Created on 2020-01-15 by the reprex package (v0.3.0)

Upvotes: 2

ThomasIsCoding
ThomasIsCoding

Reputation: 101054

Here is a base R solution

lst <- unlist(recepten,recursive = F)
dfout <- data.frame(
  recp = c("Pasta_pesto", "Broccoli_spinaziesoep", "Romige_kipcurry"),
  ing_num = lengths(lst),
  cnt_true = sapply(lst,function(x) sum(x %in% food_box)))

such that

> dfout
                   recp ing_num cnt_true
1           Pasta_pesto       4        2
2 Broccoli_spinaziesoep       2        0
3       Romige_kipcurry       4        2

Upvotes: 1

Adam Sampson
Adam Sampson

Reputation: 2011

The easiest way to do this is using rbind(). It's also very slow and loops in R aren't recommended for this type of thing (merge or join would be better). However, for homework it makes sense because you need to understand how the logic works before you start using tools to do it faster.

How to create an empty dataframe:

df1 <- data.frame(contains = character(),
                  recepten = character(),
                  foodbox = character()
       )

Creating an empty dataframe makes it easier to use in a loop because you don't have to treat the first loop (when there is no data or dataframe) differently from later loops.

Then any time you want to add a row to the dataframe you can create a new dataframe with a single row of data and then:

df1 <- rbind(df1,df2)

It's slow, but it shows the logic. I'm going to leave how/where to put it into the loop to you since this is homework.

Upvotes: 1

Related Questions