0

I feel like that title is a bit confusing so I am sorry. To explain more clearly, I want to loop through a vector full of Genre names for TV and Movies. I have a data frame with a "listed_in" column. They each have up to three genre's. I found each unique genre. Here is a small example list of genres.

genre <- c("LGBTQ+", "Mystery", "Action", "Latino", "Educational", "Kids")

From here I tried to make a function.

addColumn <- function(tbl){
  for(gen in genre){
    print(gen)
    tbl$gen <- c(0)
  }
return(tbl)
}

After doing this I thought I was done. Seemed simple enough and seemed like it would work. However, instead of the result being a table with 6 new columns of genre names and 0, I only received one new column with the name "gen" with a value of 0.

I also tried using the mutate method from dplyr in very much the same fashion to no avail.

My major question from this remains, is there a way to list through each value in a vector and create a column with that name?

Thanks for any support!

  • 1
    You can't use `$` with string column names. `data$x` will always look for a column named `"x"` whether or not you've defined `x <- "my_column_name"`. You use `[[` instead--see the linked FAQ. Or in this case, you can skip the loop and add them all at once with `your_data[genre] <- 0`. – Gregor Thomas Mar 29 '22 at 17:22
  • 1
    You could try something like `for (gen in genre) { tbl <- tbl %>% mutate({{ gen }} := 0) }`. – Martin Gal Mar 29 '22 at 17:26

0 Answers0