Adding a column to a data frame

Hello everyone!
I have homework that I do not understand how to compleat. I am supposed to use ggplot2movies library in order to create a new collumn in which there will be written what kind of movie it is. Movies look like this:
As you can see I have created new collumn called Genre, what I do not know is how to find first 1 in a row and make it write collumn name in that row of Genre. For example for first row in Genre there should be Comedy. Also if there is more 1 in a row then single one it should write in that row first Collumn's name.
I will be really thankful for any help guys


Welcome to the RStudio community!
Let me start by linking our homework policy (it's very nice of you to label is as such!)

In summary we can help you with tips and guidance, but will not provide a full solution, though we can discuss further questions.

I will provide some tips soon if no-one else has done so

Kind regards,

Please give me at least some page where i can learn how to do it

Hi, and welcome!

Check out the homework policy for this site. We don't provide answers, for obvious reasons, but I can offer you a pointer to get you started. Also, learn to include a reproducible example, called a reprex.

You've got the first step--creating a new column, and now you're stuck on the second step, filling it it, right? There are a couple of techniques you can use for this.

The first, which is more cumbersome, is to use a for loop to examine the values in each row until you get a hit, then stopping. To do this you would pipe your dataframe, which I will call movies into mutate with an ifelse test. Something like

movies %>% mutate(genre = ifelse(Action == 1, "Action, NA")) ...

repeat for each column until you get a hit, then stop.

The second way is to treat each row as a logical vector, find the position of the first TRUE and use that as an index to get the corresponding genre:

genres <- c("Action", "Animation", "Comedy", "Documentary", "Romance", "Short")
row_vector <- c(0,0,1,1,0,0,0)
indices <-min(which(row_vector == TRUE))
#> [1] "Comedy"

Created on 2019-12-17 by the reprex package (v0.3.0)

Try combining that algorithm with mutate to populate Genre

1 Like

One extra tip: note that there are rows where there are no 1 present, so you have to build in a scenario where that happens and call the genre 'unknown' or something.

Hope the tips are helping you along. Feel free to post your progress and ask new questions if you get stuck.


1 Like

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